箭头函数的this指向
情况一
const obj = {
value: 42,
regularFunction: function () {
console.log(this.value); // 输出 42
},
arrowFunction: () => {
console.log(this.value); // 输出undefined,因为this 是继承自定义时的上下文window
}
};
// 使用 bind 改变普通函数的 this 指向
const boundRegularFunction = obj.regularFunction.bind({ value: 100 });
boundRegularFunction(); // 输出 100
// 尝试使用 bind 改变箭头函数的 this 指向
const boundArrowFunction = obj.arrowFunction.bind({ value: 100 });
boundArrowFunction(); // 输出 undefined,因为箭头函数的 this 没有改变
情况二
const value = 'i am in the window'
const obj = {
arrowFun:()=>{
console.log('window:', this) // Window
console.log('value:', this.value) // undefined
console.log('window.value:',window.value) // undefined
}
}
obj.arrowFun()
虽然this指向window,但是在全局环境下定义的value不能通过this.value或者window.value的获取