When I'm calling an overridden method from the super 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 key is calling the parent's method using super.methodName();
Try it here
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.If you want a super class to call a function from a subclass, the cleanest way is to define an abstract pattern, in this manner you explicitly know the method exists somewhere and must be overridden by a subclass.
This is as an example, normally you do not call a sub method within the constructor as the sub instance is not initialized yet… (reason why you have an "undefined" in your question's example)
Test it Here
And if like @Max you really want to avoid implementing the abstract method everywhere, just get rid of it. I don't recommend this approach because you might forget you are overriding the method.
Try it Here