嘗試創建一些 Javascript 類和父類,但不確定我是否正確執行此操作,但子類中的 super() 無法正常作業。試圖讓 DivElement 中的內容正常作業,但它一直回傳未定義。
代碼:
class HTMLElement{
constructor(tag, content){
this.tag = tag;
this.content = content;
}
render(){
return `<${this.tag}>${this.content}</${this.tag}>`;
}
class DivElement extends HTMLElement{
constructor(content){
super(content);
this.tag = 'div';
}
}
let div1 = new DivElement('test');
console.log(div1);
console.log(div1.render());
uj5u.com熱心網友回復:
超級呼叫應該匹配目標方法的簽名。它應該是super('div', content);:
class HTMLElement{
constructor(tag, content){
this.tag = tag;
this.content = content;
}
render(){
return `<${this.tag}>${this.content}</${this.tag}>`;
}
}
class DivElement extends HTMLElement{
constructor(content){
super('div', content);
this.tag = 'div';
}
}
let div1 = new DivElement('test');
console.log(div1);
console.log(div1.render());
// <div>test</div>
uj5u.com熱心網友回復:
HTMLElement 類的建構式使用兩個引數(標簽和內容)呼叫。擴展類只用一個引數呼叫建構式,并將內容賦值給父類的tag引數。請注意,JS 不允許建構式多載。
請參閱甘油的答案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/462990.html
標籤:javascript 班级 遗产
