0

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();
    }
}
  • 1
    *Is it a good practice to call child method from a parent class?* Absolutely not. – Marco Luzzara Jan 23 '21 at 19:06
  • The object inheritance hierarchy is only traversed in one direction - from child to parent. There is no provision in the language for a parent to call a method of the child using the `this` keyword. – Randy Casburn Jan 23 '21 at 19:09
  • In other languages (like C++), there's the concept of a virtual method where the interface is defined in the parent and the implementation is provided by a child and then anyone in parent or child can call it, but you do NOT ever create an instance of just the parent. You can do something similar in Javascript, but it is not as common. It would be more common to provide a default implementation in the parent and then override it in the child and then no matter who calls it, they will get the overridden child version for an instance of the child. In JS, all methods are essentially "virtual". – jfriend00 Jan 23 '21 at 19:20

1 Answers1

3

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() returns undefined

That's because you have a return; statement doesn't return anything. Remove the linebreak. Don't use Allman brace style in JavaScript.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375