2 回答

TA貢獻1887條經驗 獲得超5個贊
您需要super()在您的子類中調用,正如MDN 解釋的那樣:“在構造函數中使用時, super 關鍵字單獨出現并且必須在使用this 關鍵字之前使用?!?/p>
class Renderable{
toHTML(){
return '';
}
}
class Intro extends Renderable{
constructor(title, pretitle, backgroundImage){
super()
this.title = title;
this.pretitle = pretitle;
this.backgroundImage = backgroundImage;
}
}
const intro = new Intro('title', 'pretitle', 'bg.jpg')
alert(intro.title)

TA貢獻1827條經驗 獲得超4個贊
只需添加這一行
class Intro extends Renderable{
constructor(title, pretitle, backgroundImage){
super(); // Whenever you extend a class you have to call parent constructor first
this.title = title;
this.pretitle = pretitle;
this.backgroundImage = backgroundImage;
}
[...]
}
根據MDN,在構造函數中使用時, super 關鍵字單獨出現并且必須在使用 this 關鍵字之前使用。super 關鍵字還可用于調用父對象上的函數。你可以閱讀這篇文章,以獲得更好的想法。
添加回答
舉報