【问题标题】:ECMA Script 6 Arrow functions as object propertiesECMAScript 6 箭头函数作为对象属性
【发布时间】:2014-10-23 11:44:02
【问题描述】:

我意识到这样做毫无意义,但我不明白为什么它不起作用。

var person = {
    _name: "Steve",
    doSomething: () => console.debug("Doing stuff with ", this._name)
}

"this" 绑定到全局对象,而不是调用 getName 的对象。我期待上面的内容相当于:

var person = {
    _name: "Steve",
    doSomething: function() { console.debug("Doing stuff with ", this._name) }
}

(我知道你应该这样写)

var person = {
   _name: "Steve",
   doSomething() {
      console.debug("Doing stuff with ", this._name)
   }
}

【问题讨论】:

  • “我知道你应该这样写” - 不,你不应该。
  • 奇怪:在 Chrome 版本 38.0.2125.104(64 位)中,this 仍然引用 window 对象。
  • @thefourtheye 确定你是这样称呼它的 person.getName()?
  • @thefourtheye 我想不出你为什么说你不应该使用那种风格 - 也许我使用 get 函数混淆了这个问题,假设该函数做了其他简单的返回值的事情。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 我猜,等价的应该是function() { return console.debug("Doing stuff with ", this._name) }

标签: javascript ecmascript-6 arrow-functions


【解决方案1】:

来自mdn

箭头函数捕获封闭上下文的 this 值

这与函数不同。

【讨论】:

猜你喜欢
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多