从打字稿中的超类中调用重写的方法 [英] Call an overridden method from super class in typescript
问题描述
当我从超类构造函数中调用重写的方法时,我无法正确获取子类属性的值.
When I'm calling an overridden method from the super class constructor, I cannot get a value of a sub class property correctly.
示例
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.
推荐答案
执行顺序为:
-
A
的构造函数 -
B
的构造函数
A
's constructorB
's constructor
在调用A
的构造函数_super
之后,在B
的构造函数中进行赋值:
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
}
因此发生以下情况:
var b = new B(); // undefined
b.MyvirtualMethod(); // "Test String"
您将需要更改代码以解决此问题.例如,通过在B
的构造函数中调用this.MyvirtualMethod()
,通过创建工厂方法来创建对象然后执行函数,或将字符串传递到A
的构造函数中并以某种方式进行处理. .有很多可能性.
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.
这篇关于从打字稿中的超类中调用重写的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!