ooptypescripttypescript1.4

Call an overridden method in base class constructor in typescript


When I'm calling an overridden method from the base class constructor, I cannot get a value of a sub class property correctly.

Example:

class A
{
    constructor()
    {
        this.MyvirtualMethod();
    }

    protected MyvirtualMethod(): void
    {

    }
}

class B extends A
{
    private testString: string = "Test String";

    public MyvirtualMethod(): void
    {
        alert(this.testString); // This becomes undefined
    }
}

I would like to know how to correctly override functions in typescript.


Solution

  • The order of execution is:

    1. A's constructor
    2. B's constructor

    The assignment occurs in B's constructor after A's constructor—_super—has been called:

    function B() {
        _super.apply(this, arguments);   // MyvirtualMethod called in here
        this.testString = "Test String"; // testString assigned here
    }
    

    So the following happens:

    var b = new B();     // undefined
    b.MyvirtualMethod(); // "Test String"
    

    You will need to change your code to deal with this. For example, by calling this.MyvirtualMethod() in B's constructor, by creating a factory method to create the object and then execute the function, or by passing the string into A's constructor and working that out somehow... there's lots of possibilities.