Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Class Inheritance not working as it should

Trying to create some Javascript classes and parent classes, and not sure if I’m doing this correctly, but super() in the child class isn’t working as it should. Trying to get content in DivElement to work, but it keeps returning undefined.

Code:

 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());

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The super call should match the signature of the target method. It should read 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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading