当每个类都包含具有相同名称的方法时,在访问层次结构中的方法时遇到麻烦。
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] 删除。
我来说两句