Typescript对象文字“this”关键字

时间:2016-10-26 17:40:45

标签: javascript typescript this object-literal

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

3 个答案:

答案 0 :(得分:3)

您正在使用箭头功能which has lexical this

但是,对象文字中非箭头函数属性的简写更短:

PS C:\Users\user> New-TestMultipleDefaultValues -SomeOtherThingThatIfSpecifiedShouldResultInTest1HavingValue1 "thing"
Value1
PS C:\Users\user> New-TestMultipleDefaultValues
Value2
PS C:\Users\user> New-TestMultipleDefaultValues -Test1 "test"
test

答案 1 :(得分:3)

您要求打字稿来推断thisfooObj

Typescript通过创建一个局部变量this来绑定_this,该变量绑定到this - 声明fat-arrow的上下文。在您的情况下,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;
}());

答案 2 :(得分:0)

设置"noImplicitThis": true编译器选项是您现在启用此功能的方式。 This pull request已启用在对象文字中键入this的功能。 Aleksey L最初是在对问题的评论中建议使用此编译器选项的,但当时并没有这种功能。

相关问题