this的指向问题
1、this总是指向函数的直接调用者
setInterval(function() {
this.arg = 'hello'; // 指向window
}, 1000);
let obj = {
name: 'hello',
fn: function() {
this.name = 'world';
},
fn2: function() {
return function() {
return this.name;
}
}
}
obj.fn(); // fn里的this指向obj,name被改为world
obj.fun2(); // name是undefine,fn2的this指向window
2、如果有new关键字,this指向new出来的那个对象
3、在事件中,this指向触发这个事件的对象
4、箭头函数中的this指向最近一层的对象
const obj = {
fn() {
setTimeout(function () {
setTimeout(function () {
console.log(this); // window
})
setTimeout(() => {
console.log(this); // window
})
})
setTimeout(() => {
setTimeout(function () {
console.log(this); // window
})
setTimeout(() => {
console.log(this); // obj
})
})
}
}
obj.fn();