首页 > 解决方案 > 为什么 THIS 指向 obj?

问题描述

我非常困惑在 forEach 循环中为什么 THIS 会指向 obj。

我假设将输出 return this.id is undefined,因为它在词法函数中调用。会将其指向窗口。

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);

标签: javascriptthisscopes

解决方案


的第二个参数Array.prototype.forEachthisArg. 请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach其中指出:

如果为 forEach() 提供了 thisArg 参数,它将用作回调的 this 值。


推荐阅读