Typescript对象literal "this"关键字

Typescript object literal "this" keyword

本文关键字:quot 关键字 this 对象 literal Typescript      更新时间:2023-09-26

在对象文字中的函数中使用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);
    }
} 

设置"noImplicitThis": true编译器选项是现在启用此功能的方式。这个pull请求在对象字面量中启用了类型为this的请求。Aleksey L最初在对这个问题的评论中提出了这个编译器选项,但当时它并没有这样工作。

您正在使用一个箭头函数,它具有词法this

对象文字中非箭头函数属性的简写甚至更短:

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

这个答案在提问时是正确的。自从typescript的新版本和目标javascript版本改变后,

你要求typescript推断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 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;
}());