TS/JS 箭头函数更改“this”的值

TS/JS arrow function changing value of `this`?

本文关键字:this 的值 函数 JS TS      更新时间:2023-09-26

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

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

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

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