首页 > 解决方案 > 关于 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...我无法理解。

标签: javascriptarrow-functions

解决方案


回答

箭头函数没有内部上下文 (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


推荐阅读