函数中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对象,21
箭头函数:
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();
箭头函数:
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指向定义生效时所在的对象。