首页 > 解决方案 > 为什么在这段代码中,箭头函数的外部作用域是 `showList` 而不是 `forEach`?

问题描述

下面是这个现代 JavaScript 教程的代码片段:

let group = {
  title: "Our Group",
  students: ["John", "Pete", "Alice"],

  showList() {
    this.students.forEach(
      student => alert(this.title + ': ' + student)
    );
  }
};

group.showList();

本教程试图this用箭头函数进行解释,它说:

这里在forEach中使用了箭头函数,所以this.title在里面和在外部方法showList中完全一样。即:group.title。

我们知道this箭头函数是由词法确定的。所以范围链应该是:

global--> showList-->forEach-->arrow function

在这种情况下,箭头函数的外部范围应该是forEach而不是showList。因此this在箭头函数中与在中完全相同forEach,这应该是undefined因为没有thisArg传递到forEach。但实际上thisis group,意思就是和 in 完全一样showList。那么,在这种情况下似乎forEach没有范围?我很困惑。

标签: javascriptthis

解决方案


发生错误是因为 forEach 默认使用 this=undefined 运行函数,因此尝试访问 undefined.title。

这不会影响箭头功能,因为它们只是没有这个。

来源https://javascript.info/arrow-functions

正如我们在对象方法一章中所记得的,“this”,箭头函数没有 this。如果访问,则从外部获取。

在这种情况下,外部函数showList就像您将意识到的那样,forEach 在这里不是箭头函数的包装函数,而只是对带有回调的函数的调用。

取而代之showList的是包装功能。因此它继承自showList

也许这个例子会帮助你更好地理解:

'use strict';

function hello(greet) {
  greet()
}

let group = {
  title: "Our Group",
  students: ["John", "Pete", "Alice"],


  showList() {
    hello(() => console.log("Hello " + this.title))
  }
};

group.showList();


推荐阅读