jokul
jokul

Reputation: 1339

How to access 'this' in overridden method?

I have an abstract class which exposes a method:

public abstract class Foo {
    public update(){
        //do some stuff
    }
}

Which this class inherits from:

public class Doo extends Foo {
    public update(){
        super.update();
        const x = this.getValue(); //problem line
    }
}

Now, since update() is exposed, it's being executed in a different context, and so that this on the "problem line" is referencing the calling object, a problem I'd normally solve by declaring update() in the abstract parent as an arrow method:

public class Foo {
    public update = () => {
       //call this all i want
    }
}

However, if I do this, I can no longer call super() from the child class. Is there any way to call super.update() and maintain control over this?

Upvotes: 1

Views: 60

Answers (1)

Samuel Neff
Samuel Neff

Reputation: 74909

Unfortunately the best thing you can do is create two methods--one for overriding and one for public. Put implementation in the overriding method as you have it but expose a separate method using arrow functions that calls this.otherMethod(). that way you're preserving this for the public method and preserving super for the implementation.

This is not really a TypeScript issue but a JavaScript one.

Upvotes: 1

Related Questions