javascript - 关于 JavaScript 中的箭头函数
问题描述
对箭头函数的工作方式感到困惑......在这个特定的例子中:
class VillageState {
constructor(place, parcels) {
this.place = place;
this.parcels = parcels;
}
move(destination) {
if (!roadGraph[this.place].includes(destination)) {
return this;
} else {
let parcels = this.parcels.map(p => {
if (p.place != this.place) return p;
return {place: destination, address: p.address};
}).filter(p => p.place != p.address);
return new VillageState(destination, parcels);
}
}
}
特别是,
let parcels = this.parcels.map(p => {
if (p.place != this.place) return p;
return {place: destination, address: p.address};})
我能说的是 p 是这个箭头函数的参数,但在这个例子中它将被替换为什么变量?move 方法中的唯一参数是destination,但这不会取代p...我无法理解。
解决方案
回答
箭头函数没有内部上下文 (this),因此当您需要从函数外部访问上下文时,它们非常有用。
在这种情况下,您在地图中使用箭头函数并从类访问上下文(因为 move 是 VillageState 上的一个方法,它也可以访问this.place
为什么这很酷?好吧,如果您使用常规函数并尝试访问this.place
,您将得到一个 ReferenceError,因为在本地 this 上没有定义位置变量。
// dont do this at home
function mapFn(p) {
/* This here is inside the mapFn and since this.place is not defined
we get a ReferenceError */
if (p.place != this.place) return p;
return {place: destination, address: p.address};
}
let parcels = this.parcels.map(mapFn)
/* Hopefully the syntax above isn't confussing:
* mapFn will be called by default with all the map() parameters
* inside mapFn we only need p so that's the only name param used
*/
资源
要了解有关箭头函数的更多信息,我会查看 Impatient JS,这是一个非常深入的解释,因此它应该回答您的大部分问题。整个“可调用值”一章非常有用。还有MDN。
https://exploringjs.com/impatient-js/ch_callables.html#arrow-functions
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
推荐阅读
- jboss - 禁用 TLS V1.1,在 WildFly 20.0.1 上仅启用 TLSv1.2
- ruby-on-rails - Rails 6 纱线库不会在生产中加载
- selenium-webdriver - OKTA 应用程序的 API 自动化
- vb.net - VB.Net 公共财产
- html - 在桌面和移动布局上组织响应式图像
- c++ - 从csv文件c ++中删除一行
- r - 在R中计算过去3周的平均值和标准同一天
- bash - 如何获取文件夹的用户权限并将其分配给Linux中的另一个文件夹
- docker - V1 到 V2 路径前缀
- python - 找不到元素时,如何在本网站上使用 Python Selenium webdriver 单击按钮?