Scipion
Scipion

Reputation: 11888

Is there a way to avoid the infamous that = this in typescript

I was wondering if typescript provides a way to avoid the infamous :

let that = this

By instance, I have a class calling a web api to which I am subscribing, and to have my reference of the class in the subscribe, I did create a variable for the this.

class Foo {
   f = {}
   let that = this 
   this.http.get(foo)
   .subscribe {
      res => that.f = res 
   }
}

Upvotes: 3

Views: 4097

Answers (1)

David Sherret
David Sherret

Reputation: 106710

Yes. The let that = this is not necessary when using an arrow function. An arrow function lexically binds the this value.

Observe that when writing this code:

class Foo {
    f = {};

    someMethod() {
        someFunction(res => this.f = res)
    }
}

The ES5 JavaScript output does the let that = this for you (as var _this = this):

var Foo = (function () {
    function Foo() {
        this.f = {};
    }
    Foo.prototype.someMethod = function () {
        var _this = this;
        someFunction(function (res) { return _this.f = res; });
    };
    return Foo;
}());

Upvotes: 8

Related Questions