调用超超类的方法

米洛711

当每个类都包含具有相同名称的方法时,在访问层次结构中的方法时遇到麻烦。

class A { 
    constructor(private name: string) { }
    notify() { alert(this.name) }
}

class B extends A { 
    constructor() {
        super("AAA")
    }

    notify() {alert("B") }
}

class C extends B { 
    notify() { alert("C") }

    callA() {
        this.notify(); // this alerts "C"
        super.notify(); // this alerts "B"

        // How to call notify() of the class A so it alerts "AAA"? 
    }
}

new C().callA();
提香·切尔尼科娃·德拉戈米尔

当我质疑要求您执行此操作的设计时,您可以通过获取A.prototype和使用call以下方法的原始方法来轻松实现这一点

class C extends B { 
    notify() { alert("C") }

    callA() {
        A.prototype.notify.call(this);
    }
}

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章