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.
The order of execution is:
A's constructorB's constructorThe assignment occurs in
B's constructor afterA's constructor—_super—has been called:So the following happens:
You will need to change your code to deal with this. For example, by calling
this.MyvirtualMethod()inB's constructor, by creating a factory method to create the object and then execute the function, or by passing the string intoA's constructor and working that out somehow... there's lots of possibilities.