Reputation: 89
Is it a good practice to call child method from a parent class? At this actual example in BaseComponent.js the call to this.constructHtml(); returns undefined. What am I missing here? Thanks!
script.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();
}
}
Upvotes: 0
Views: 1595
Reputation: 665545
Is it a good practice to call child method from a parent class?
Yes, this is totally normal. However, your base class should either provide a default implementation for constructHtml
, or declare it as abstract (in TypeScript). To be precise, it is only a good practice to call methods declared on the class itself, although they might be (or even expected to be) overridden in a subclass.
the call to
this.constructHtml()
returnsundefined
That's because you have a return;
statement doesn't return anything. Remove the linebreak. Don't use Allman brace style in JavaScript.
Upvotes: 3