我在TypeScript中编写了这样的对象文字:
var object = {
message: "Say",
say: () => {
return this.message;
}
};
我得到了这样生成的JavaScript:
var object = {
message: "Say",
say: function () {
return _this.message;
}
};
在返回声明之前不应该有这样的行:
var _that = this;
因为我正在使用箭头函数表达式?
答案 0 :(得分:2)
你是对的。它错过了:
var _this = this;
这是在发布(0.8)之后发现的,目前已在开发人员分支上修复。
注意: 我想你也想写
var object = {
message: "Say",
say: function () {
return () => this.message;
}
};
将实际打印说出它运行时。 请参阅:http://wiki.ecmascript.org/doku.php?id=harmony:arrow_function_syntax
答案 1 :(得分:2)
=>
在这里有点危险,因为关键是,将this
绑定到封闭范围的this
。在正确的代码生成中,var _this = this;
行高于对象文字,而say
函数只返回undefined
。
当您真正想要引用封闭范围中存在的this
时,您只想在=>
表达式中使用this
。在这种特殊情况下,你没有(你想要内部范围this
,即对象文字本身。)