简体   繁体   中英

Typescript object literal “this” keyword

What's the expected behavior when using this inside a function in an object literal?

For example, let's say I have a type foo that only has a function named bar and no other property on it. 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. Shouldn't typescript error out, as fooObj does not have baz on it?

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. This pull request enabled typed this in object literals. Aleksey L originally suggested this compiler option in a comment on the question, but at the time it didn't function that way.

You're using an arrow function, which has lexical 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.

You are asking typescript to infer that this is fooObj .

Typescript binds this by creating a local variable _this , that is bound to the this -context where the fat-arrow is declared. And in your case, this is the global scope, which is 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;
}());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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