从子类调用函数的超类

加巴罗斯

我有一个带有两种方法的基类,“A”和“B”。

方法“B”在基数中调用“A”。然后我有一个覆盖“A”方法的子类。当我从子类调用方法“B”时,会调用基类中的方法“A”。

super 有没有办法从子类调用重写的方法?

export class SuperClass {
    A(param: any): string {
        return "A called from base";
    }

    B(param: any): string {
        let value = this.A(param);
        console.log(value);

        return "B called from base";
    }
}

export class SubClass extends BaseClass  {
    A(param: any): string {
        return "A called from subclass";
    }
}

// create a subclass
let bInstance = new B();
bInstance.B(someParam); // I want to call the overriden A in the subclass

PD:基类中的“A”需要有自己的实现,不能是抽象的

马克斯·科列茨基

bInstance.B(someParam); // 我想在子类中调用被覆盖的 A

它将调用A子类中的重写方法,因为this它将指向 的实例,SubClass而 JS 将首先A在此实例上查找方法所以这段代码:

B(param: any): string {
    let value = this.A(param);
    console.log(value);

应该登录 "A called from subclass";

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章