[英]How to call a constructor method of Parent class from child prototype in javascript?
[英]Call child method from parent class Javascript
從父 class 調用子方法是一種好習慣嗎? 在 BaseComponent.js 中的這個實際示例中,調用 this.constructHtml(); 返回未定義。 我在這里想念什么? 謝謝!
腳本.js
import Header from './components/Header.js';
const headerEl = document.querySelector('.header');
const header = new Header(headerEl);
header.render();
Header.js
import BaseComponent from './BaseComponent.js'
export default class Header extends BaseComponent {
constructor(element)
{
super(element);
this.element = element;
}
constructHtml() {
return
`
<header>
<h1>Todo App</h1>
</header>
`;
}
}
BaseComponent.js
export default class BaseComponent {
constructor(element) {
this.element = element;
}
render(){
this.element.innerHTML += this.constructHtml();
}
}
從父 class 調用子方法是一種好習慣嗎?
是的,這完全正常。 但是,您的基礎 class 應該為constructHtml
提供默認實現,或者將其聲明為抽象(在 TypeScript 中)。 准確地說,調用在 class 本身上聲明的方法只是一種好習慣,盡管它們可能(甚至預期)在子類中被覆蓋。
調用
this.constructHtml()
返回undefined
那是因為你有return;
聲明不返回任何東西。 刪除換行符。 不要在 JavaScript 中使用 Allman 支撐樣式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.