Miguerurso
Miguerurso

Reputation: 125

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

Upvotes: 1

Views: 242

Answers (2)

Glycerine
Glycerine

Reputation: 7347

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);  // changed here
    this.tag = 'div';
   }

 }

let div1 = new DivElement('test');
console.log(div1);
console.log(div1.render());
// <div>test</div>

Upvotes: 5

Arne
Arne

Reputation: 50

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.

Upvotes: 1

Related Questions