Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

Call child method from parent class Javascript

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();
    }
}
question from:https://stackoverflow.com/questions/65863265/call-child-method-from-parent-class-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...