我非常困惑在 forEach 循环中为什么 THIS 会指向对象。
我假设会输出 return this.id is undefined ,因为它调用了一个词法函数。 THIS 会将其指向窗口。
function foo(el) {
console.log( el, this.id);
}
var obj = {
id: "awesome"
};
[1, 2, 3].forEach( foo, obj );
// 1 "awesome" 2 "awesome" 3 "awesome"
// Easy way to check
[1, 2, 3].forEach( function(el){
console.log( el, this.id);
}, obj);
最佳答案
Array.prototype.forEach
的第二个参数是 thisArg
。参见 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach其中指出:
If a thisArg parameter is provided to forEach(), it will be used as callback's this value.
关于javascript - 为什么这个点在 obj 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59332800/