js 普通函数,构造函数,匿名函数,闭包函数,箭头函数

博客主要介绍了JavaScript中普通函数和箭头函数的相关知识。给出普通函数示例,展示this指向window的情况。详细阐述箭头函数的多种形式,如单参数、无参数、多参数等,还说明了箭头函数没有this、arguments和prototype,以及其返回值的不同写法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//普通函数
function person2 (name,age) {
console.log(‘this:’,this)
this.name=name;
this.age=age;
my = ‘dhk’
this.sayName=function () {
console.log(this.name);
}
console.log(this.age);
}
var person = person2(“lucy”,“23”); //this 指向window
window.sayName(); //luck

    //构造函数
    function Person (name,age) {   //一般都是首字母大写
		this.name=name;
		this.age=age;
		this.sayName=function (){
			console.log(this.name);
		}
	}
	var personw =new Person("make","18");   //new 一个对象    this指向Person
	personw.sayName();   //make


    //匿名函数
    (function(){
		console.log("匿名函数自我调用");
	})();  //调用匿名函数

	// 将匿名函数赋值给变量
	var cat = function () {
		console.log("赋值的匿名函数");
	}
	cat();


    //闭包
    var mybox = (function box (n) {
		return function(x){
			return n+x;
		}
	})('测试')
	console.log(mybox('dddd'));

//箭头函数
x => x * x; //相当于 function(x){return xx}
()=> 36;
(x,y)=>x*y;

//箭头函数闭包
var a = 10;
var foo = (a => (() => a++))(a);
foo()

箭头函数没有this,是继承上级的this
function f(){
this.a =1
return ()=> console.log(this.a)
}
f()() // 1

箭头函数没有arguments,是继承上级的arguments
function f(){
return ()=> console.log(arguments)
}
f(1,2)(3,4) // [1,2]

箭头函数没有prototype

箭头函数返回值
默认返回 const fun2 = ()=> 1+2; //return 3
如果是块语句必须写return, const fun2 = ()=> {return 1+2} //return 3
如果返回是对象,不想写return,可以用 ()包裹
const fun2 = ()=> ({a:2}) // return a:2
或者写全return
const fun2 = ()=> {return {a:2}} // return a:2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端段

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值