var id =21;
function testThis(){
setTimeout(function(){
console.log(this.id);
},1000);
}
let testThis2 = ()=>{
setTimeout(function(){
console.log(this.id);
},1000);
}
function testThis3(){
setTimeout(()=>{
console.log(this.id);
},1000);
}
testThis();
testThis2();
testThis3();
testThis.call({id:42});
testThis2.call({id:42});
testThis3.call({id:42});
为什么 testThis2.call({id:42}); console的是21呢。
因为看this首先看它所在的function, testThis2表面上自身是用了箭头函数,但只能说,testThis2的函数执行内容里的this可以按.call({id:42})绑定,而setTimeout里面还有一个function,里面的this是要看这个内部function的,不会去看testThis2的this的。
所以才有
testThis3
的做法嘛~