使用 TypeScript v1.7.5,上下文this
似乎变得混乱,或者可能没有正确转译。或者我错过了一些东西。箭头函数的内部this
正在发生变化,当我期望它仍然this
与函数外部相同时。我已经调试了这种情况,结果显示在下面的评论中。
来源 TS
// Debug: "this" is an instance of the class -- good.
FS.exists(dbPath, (exists: boolean) => {
// Debug: "this" is an instance of the global object -- not good.
...
});
生成的 JS (ES5)
FS.exists(dbPath, function (exists) {
...
});
我期待生成的 JS 将回调绑定如下:
FS.exists(dbPath, function (exists) {
...
}.bind(this));
我需要保留this
回调内部的值,因此我在整个代码中使用箭头函数。但我很困惑为什么这似乎不能正常工作。
笔记
当且仅当我特别尝试this
在箭头函数中使用时,TypeScript 会创建此解决方法:
var _this = this;
FS.exists(dbPath, function (exists) {
var _x = this;
});
好的,很好,但是使用绑定不是更好吗?这仍然不能解决我从箭头函数中调用函数的问题。这些函数调用将丢失 的上下文this
,这不是适当的行为。