先看下代码:
let arr = [1, 2, 3];
let obj = {
add: (x) => {
return x + 1;
},
};
// thisArg 对于箭头函数没有作用
arr.forEach((item, index) => {
console.log(this); // window
console.log(this.add(item)); // 报错
}, obj);
// thisArg 在普通函数中起作用
arr.forEach(function (item, index) {
console.log(this); // obj
console.log(this.add(item));
}, obj);
// 不传值,则为 window
arr.forEach(function (item, index) {
console.log(this); // window
});
==> 看一下 MDN 上对于 forEach 方法的说明:
如果 thisArg 参数有值,则每次 callback 函数被调用时,this 都会指向 thisArg 参数。如果省略了 thisArg 参数,或者其值为 null 或 undefined,this 则指向全局对象。