this 有很多应用场景:
- 函数中
- call、apply、bind
- class
- 对象中
- 箭头函数中
案例
// 对象中
const zhangsan = {
name: "zhangsan",
sayHi() {
console.log(this);
},
wait1() {
setTimeout(function () {
console.log(this);
});
},
wait2() {
setTimeout(() => {
// this 即当前对象,箭头函数中 this 指向上级作用域的 this,和 sayHi 中 this 一样
console.log(this);
});
},
};
zhangsan.sayHi(); // 当前 zhangsan 对象
zhangsan.wait1(); // window, setTimeout 里面的函数执行,是 setTimeout 本身触发的执行,并非是当前对象触发
zhangsan.wait2(); // 当前 zhangsan 对象