javascript - 为什么在这段代码中,箭头函数的外部作用域是 `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
。但实际上this
is group
,意思就是和 in 完全一样showList
。那么,在这种情况下似乎forEach
没有范围?我很困惑。
解决方案
发生错误是因为 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();
推荐阅读
- python - 如何在python数据框中的列上编写和循环列表?
- azure - 限制 Azure 中的应用注册权限
- javascript - 在“chrome.tabs.executeScript()”中传递选项卡 ID
- angular - Angular Material Date-Picker 无法正常工作
- javascript - Now 2 迁移的问题
- android - 构建 android 应用程序和生成 APK 文件的最小依赖项
- android - 在模块 classes.jar com.google.android.gms:play-services-measurement-impl 中找到重复的类 com.google.android.gms.internal.measurement.zzdu:
- angular - 具有先前路由的 ngrx-router-store
- javascript - 脚本标签内的异步脚本 src,符合 GDPR 的谷歌广告
- reactjs - 测试一个使用 Resize Observer 的 React Hook