【发布时间】: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