javascript 之 回调函数(普通函数和箭头函数)中的this

转载自:https://blog.csdn.net/qq_33745501/article/details/80223841

函数中this对象的取值,是在函数被调用执行的时候确定的。此时会创建执行上下文环境。

对于箭头函数,它没有自己的this,不能用作构造函数。箭头函数中的this对象是定义时所在的对象,

不是调用时所在的对象。

对于回调函数中的this对象。以下是两个小例子。

1.对于 setTimeout函数

普通函数: 100ms后执行时,this指向window对象。

function foo() {
	setTimeout(function() {
		console.log(this);
		console.log("id: ",this.id);
		}, 100);
	}
	var id=21;
foo();                   //this指向window对象, 21     

foo.call({id:42});        //this指向window对象&#xff0c;21 </code></pre>

箭头函数:

function foo() {
	setTimeout(() =>{
		 console.log(this);
		 console.log("id: ",this.id);
	}, 100);
}
 var id=21;
 foo();           //this指向window
 foo.call({id:42});       //this指向{id:42}对象
箭头函数:this是在定义时生效的。this总是指向函数定义生效时所在的对象。


2.对于事件处理函数

普通函数:

 var handler={
		 	id:'123456',
		 	init:function () {
		 		document.addEventListener('click', function(e) {
		 			this.doSomething(e.type);                       //this指向window对象。所以会出错
		 		},false);
		 	},
		 	doSomething:function (type) {
		 		console.log("handler"+type+"for"+this.id);
		 	}
		 };
	 handler.init();</code></pre>箭头函数&#xff1a;
         var handler={
		 	id:'123456',
		 	init:function () {
		 		document.addEventListener('click', (e)=> {
		 			this.doSomething(e.type);                  //this指向handler
		 		},false);
		 	},
		 	doSomething:function (type) {
		 		console.log("handler"+type+"for"+this.id);
		 	}
		 };

		 handler.init();

3.总结:

对于回调函数中的this对象。对于普通函数,this指向调用时所在的对象(即window对象)。对于箭头函数,this指向定义生效时所在的对象。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值