简体   繁体   English

打字稿对象文字“this”关键字

[英]Typescript object literal “this” keyword

What's the expected behavior when using this inside a function in an object literal?在对象字面量的函数中使用this时的预期行为是什么?

For example, let's say I have a type foo that only has a function named bar and no other property on it.例如,假设我有一个foo类型,它只有一个名为bar的函数,没有其他属性。 But in the fooObj.bar method, I'm able to access this.baz (where baz is not a property on type foo ) I see no error.但是在fooObj.bar方法中,我可以访问this.baz (其中baz不是foo类型的属性)我看不到任何错误。 Shouldn't typescript error out, as fooObj does not have baz on it?不应该打字稿错误,因为fooObj上没有baz吗?

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

Setting the "noImplicitThis": true compiler option is how you would enable this functionality now.设置"noImplicitThis": true编译器选项是您现在启用此功能的方式。 This pull request enabled typed this in object literals.此拉取请求启用在对象文字中键入this Aleksey L originally suggested this compiler option in a comment on the question, but at the time it didn't function that way. Aleksey L 最初在对该问题的评论中建议了这个编译器选项,但当时它并没有那样工作。

You're using an arrow function, which has lexical this .您正在使用具有词法this的箭头函数。

The shorthand for a non-arrow function property in an object literal is even shorter, though:但是,对象字面量中非箭头函数属性的简写甚至更短:

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

This answer was true at the time of the question.这个答案在提问时是正确的。 This have since changed with new versions of typescript and target javascript versions.这已经随着新版本的打字稿和目标 javascript 版本而改变。

You are asking typescript to infer that this is fooObj .您要求打字稿推断thisfooObj

Typescript binds this by creating a local variable _this , that is bound to the this -context where the fat-arrow is declared.打字稿结合this通过创建一个局部变量_this ,绑定到this -context脂肪在哪儿箭头声明。 And in your case, this is the global scope, which is any .在您的情况下, this是全局范围,即any This is what it gets compiled into:这是它被编译成的内容:

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

This is how it looks like within a 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;
}());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM