【问题标题】:Why THIS point in the obj?为什么 THIS 指向 obj?
【发布时间】:2020-04-07 12:14:48
【问题描述】:

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

我假设将输出 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);

【问题讨论】:

  • 您明确告诉它使用obj 作为this。这就是 forEach 的第二个参数是 for
  • 在forEach方法里面,第二个参数应该是数组的Index。为什么 Object 变量可以在第二个参数中使用?
  • 请看forEach syantax developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 第一个参数是回调函数,第二个参数是执行回调时this的值。
  • 太棒了。共享 forEach 语法规则。

标签: javascript this scopes


【解决方案1】:

Array.prototype.forEach 的第二个参数是thisArg。请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach 声明:

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

【讨论】:

  • 太好了。我明白了。
猜你喜欢
  • 2018-01-15
  • 1970-01-01
  • 2012-04-27
  • 2016-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-05
  • 2016-10-29
相关资源
最近更新 更多