var obj = {
a: 2,
}
var a = 3;
const func = () => {
console.log(this.a);
}
function test() {
setTimeout(func, 100);
}
function test2() {
setTimeout(() => {
console.log(this.a);
}, 100);
}
test.call(obj); //3
test2.call(obj); //2
Run Code Online (Sandbox Code Playgroud)
看起来test和test2是一样的,但是返回的结果不同,‘this’有什么问题呢?
使用test arrow函数,this将引用该window对象,并且 as var a = 3,a将被分配为属性window,它会像
window.a
Run Code Online (Sandbox Code Playgroud)
但 intest2 this将引用该obj对象。