Ashish Sapkale
Ashish Sapkale

Reputation: 550

Typescript use of this keyword

We are using typescript for our development. I have also got a review comment that we should not 'this' keyword, it hampers performance. Orignal Code:

export Class MyClass
    {
    public myMethod1(Data) {     
            this.myMethod2();
        }

    public myMethod2() {
        }
    }

We are using like below to access 'this'. After Change:

export Class MyClass
{
public myMethod1(Data) {
        let self = this;
        self.myMethod2();
    }

public myMethod2() {
    }
}

So could you please help with implication of using 'this' keyword.

Upvotes: 0

Views: 69

Answers (1)

frogatto
frogatto

Reputation: 29285

This has no effect on performance. But using a variable called self and initialize it with this at the beginning of each class method may help to avoid unwanted behaviors. For example:

Class MyClass
{
    public foo () {
        const self = this;

        callMeLater(function (){
            console.log(self); // "self" is always the instance of MyClass
            console.log(this); // "this" may refer to another object!
        });
    }
}

In this example, self is captured while it holds a reference to the MyClass instance and in the callback function it still points to the MyClass instance, but in the callback function this may refer to something else, it depends on how the callback function is called.

Upvotes: 1

Related Questions