Typescript 对象文字 "this" 关键字

Typescript object literal "this" keyword

在对象字面量的函数中使用 this 时的预期行为是什么?

例如,假设我有一个类型 foo,它只有一个名为 bar 的函数,没有其他 属性。但是在 fooObj.bar 方法中,我能够访问 this.baz(其中 baz 不是类型 foo 上的 属性),我没有看到任何错误。打字稿不应该出错,因为 fooObj 上面没有 baz

type foo = {
    bar(): void;
}
var fooObj: foo = {
    bar: () => {
        // TS does not error out when I access this.baz
        console.log(this.baz);
    }
} 

您正在使用箭头函数,which has lexical this

对象字面量中非箭头函数 属性 的 shorthand 甚至更短,不过:

var fooObj: foo = {
    bar() {
        console.log(this.baz);
    }
}

这个答案在提问时是正确的。这已经随着新版本的打字稿和目标 javascript 版本而改变。

您要求打字稿推断 thisfooObj

Typescript 通过创建局部变量 _this 来绑定 this,该变量绑定到声明胖箭头的 this 上下文。在您的例子中,this 是全局范围,即 any。这就是它被编译成的内容:

var _this = this;
var fooObj = {
    bar: function () {
        // TS does not error out when I access this.baz
        console.log(_this.baz);
    }
};

这是 class 中的样子:

class Bar
{
    private var = 23;
    public makeSound = () => console.log(this.var) 
}

// Compiles into:

var Bar = (function () {
    function Bar() {
        var _this = this;
        this.var = 23;
        this.makeSound = function () { return console.log(_this.var); };
    }
    return Bar;
}());

设置 "noImplicitThis": true 编译器选项是您现在启用此功能的方式。 This pull request 在对象文字中启用类型 this。 Aleksey L 最初在对该问题的评论中建议了这个编译器选项,但当时它并没有那样工作。