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呢。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
因为看this首先看它所在的function, testThis2表面上自身是用了箭头函数,但只能说,testThis2的函数执行内容里的this可以按.call({id:42})绑定,而setTimeout里面还有一个function,里面的this是要看这个内部function的,不会去看testThis2的this的。
所以才有
testThis3
的做法嘛~箭头函数有几个使用注意点。
(1)函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
(2)不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。
(3)不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用Rest参数代替。
(4)不可以使用yield命令,因此箭头函数不能用作Generator函数。
上面四点中,第一点尤其值得注意。this对象的指向是可变的,但是在箭头函数中,它是固定的。
http://es6.ruanyifeng.com/#do...箭头函数 用之前多看看
因为在箭头函数中,this的指向是固定的,在testThis2函数是引用,引用的是箭头函数,箭头函数的this指向外面的21,所以此时this指向windows对象