1

我意识到这是一件毫无意义的事情,但我不明白为什么它不起作用。

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)
   }
}
4

1 回答 1

1

来自mdn

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

这与函数不同。

于 2014-10-23T11:49:46.140 回答