Home > Software engineering >  Javascript Class Inheritance not working as it should
Javascript Class Inheritance not working as it should

Time:04-24

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

CodePudding user response:

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>

CodePudding user response:

The constructor of the HTMLElement class is called with two parameters (tag & content). The extended class calls the constructor with only one parameter and assigns content to the tag parameter of the parent class. Note that JS does not allow constructor overloading.

See the answer of Glycerine.

  • Related