如果你想有一個超類中調用子類中的功能,最徹底的方法是定義一個抽象的圖案,以這種方式,你明確地知道方法的某處存在,必須重寫由一個子類。
這是作爲一個例子,通常你不會在構造函數中調用子方法,子實例尚未初始化......(爲什麼你有你的問題的例子是「不確定」)
abstract class A {
// The abstract method the subclass will have to call
protected abstract doStuff():void;
constructor(){
alert("Super class A constructed, calling now 'doStuff'")
this.doStuff();
}
}
class B extends A{
// Define here the abstract method
protected doStuff()
{
alert("Submethod called");
}
}
var b = new B();
測試它Here
如果@Max你真的想要避免在任何地方實現抽象方法,只是擺脫它。我不推薦這種方法,因爲你可能會忘記你重寫了這個方法。
abstract class A {
constructor() {
alert("Super class A constructed, calling now 'doStuff'")
this.doStuff();
}
// The fallback method the subclass will call if not overridden
protected doStuff(): void {
alert("Default doStuff");
};
}
class B extends A {
// Override doStuff()
protected doStuff() {
alert("Submethod called");
}
}
class C extends A {
// No doStuff() overriding, fallback on A.doStuff()
}
var b = new B();
var c = new C();
試試吧Here
在調用構造函數的虛方法被認爲是在任何OOP語言不好的做法:https://google.com/search?q=virtual+method+in+constructor –