-1

使用 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,这不是适当的行为。

4

1 回答 1

1

这看起来像是 Typescript 编译器所期望的行为。

ES6 胖箭头函数=> 实际上并不绑定this。相反,this实际上落入了上层范围。与 相同arguments,您不能在胖箭头函数中使用它,因为它们将落入上层范围。

因此,根据规范,始终绑定将是不正确的行为。this如果您不使用函数,则始终从函数内部的父作用域引用它是一种不受欢迎的行为。这看起来像是 TypeScript 编译器的正确优化。

于 2016-01-24T03:49:09.940 回答