为什么要在obj中指向这一点?

问题描述 投票:1回答:1

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

我假设将输出返回this.id为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);
javascript this scopes
1个回答
1
投票

Array.prototype.forEach的第二个参数是thisArg。参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach,其中指出:

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

© www.soinside.com 2019 - 2024. All rights reserved.