【问题标题】:Arrow function in Javascript Object [duplicate]Javascript对象中的箭头函数[重复]
【发布时间】:2017-04-19 08:48:10
【问题描述】:
let objNewWay = {
  width:400,
  height:300,
  area: () => this.width*this.height
};

console.log(objNewWay.area()); // NaN

let objOldWay = {
  width:400,
  height:300,
  area: function() {
    return this.width*this.height;
  }
};

console.log(objOldWay.area()); // 120000

我不明白为什么 Javascript 对象中的箭头函数似乎不起作用。如果你看上面的代码,第一个 console.log 打印 NaN,第二个打印出预期的数字。

https://jsbin.com/pazazikayi/edit?js,console

【问题讨论】:

  • 它叫Arrow functions不是lamda
  • 来自 MDN两个因素影响了箭头函数的引入:更短的函数和this 的非绑定。 b>
  • 谢谢。我已将问题从 lambda 更改为数组函数。
  • arrow 函数,而不是 array 函数。

标签: javascript ecmascript-6 arrow-functions


【解决方案1】:

来自documentation

箭头函数表达式的语法比函数短 表达式并且不绑定它自己的thisargumentssuper,或 新目标。这些函数表达式最适合非方法 函数,它们不能用作构造函数。

你必须使用你已经展示过的旧方法

area: function() {
   return this.width*this.height;
}

如果你还想使用箭头函数,你必须调用对象本身

let objNewWay = {
  width:400,
  height:300,
  area: ()=> objNewWay.width*objNewWay.height
};

console.log(objNewWay.area()); // NaN

【讨论】:

  • 谢谢。那么造成差异的设计考虑因素是什么?
  • @ElgsQianChen 点击文档的链接 - 你会看到 $No binding of this*
  • @ElgsQianChen 别忘了勾选答案
【解决方案2】:

arrow functions 不是 lambda,您使用它的方式将引用与您的对象不同的范围。

例如,从控制台:

let theObj = {
    whereAmI: () => console.log(this)
}

theObj.whereAmI();

// Window...

如果要使用this关键字,请使用area: function(){}方式。

【讨论】:

    猜你喜欢
    • 2018-02-07
    • 2021-03-29
    • 2020-08-13
    • 2020-11-08
    • 2020-03-07
    • 2023-03-12
    • 2023-03-08
    • 2017-06-25
    • 2019-09-27
    相关资源
    最近更新 更多