从打字稿中的超类中调用重写的方法 [英] Call an overridden method from super class in typescript

查看:88
本文介绍了从打字稿中的超类中调用重写的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从超类构造函数中调用重写的方法时,我无法正确获取子类属性的值.

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.

推荐答案

执行顺序为:

  1. A的构造函数
  2. B的构造函数
  1. A's constructor
  2. B'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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆