1

I have two very simple classes in my Javascript code:

class Renderable{
    toHTML(){
        return '';
    }
}


class Intro extends Renderable{
    constructor(title, pretitle, backgroundImage){
        debugger;
        this.title = title;
        this.pretitle = pretitle;
        this.backgroundImage = backgroundImage;
    }
    [...]
}

The code is in order this way, so there shouldn't be any hoisting issues. However, when I load my web page I get the following error:

ReferenceError: Cannot access uninitialized variable. at the line this.title = title; in the constructor. When I break on the debugger, I see that this is indeed undefined. What am I doing wrong?

Can Poyrazoğlu
  • 33,241
  • 48
  • 191
  • 389
  • I get "ReferenceError: must call super constructor before using 'this' in derived class constructor" which should point you into the right direction. – str Oct 24 '19 at 10:50
  • @str yeah, just figured it out. the tutorial that I was following was plain wrong, with examples of derived classes that don't call super at all. – Can Poyrazoğlu Oct 24 '19 at 10:58

2 Answers2

4

You need to call super() in your child class, as MDN explains: "When used in a constructor, the super keyword appears alone and must be used before the this keyword is used."

class Renderable{
    toHTML(){
        return '';
    }
}


class Intro extends Renderable{
    constructor(title, pretitle, backgroundImage){
        super()
        this.title = title;
        this.pretitle = pretitle;
        this.backgroundImage = backgroundImage;
    }
}
const intro = new Intro('title', 'pretitle', 'bg.jpg')
alert(intro.title)
Damian Peralta
  • 1,846
  • 7
  • 11
  • yeah, that was it. I was checking some docs from https://javascript.info/class-inheritance and it didn't have constructors of derived classes that explicitly call super, so I thought it wasn't needed. thanks. – Can Poyrazoğlu Oct 24 '19 at 10:59
2

Just add this line

class Intro extends Renderable{
    constructor(title, pretitle, backgroundImage){
        super(); // Whenever you extend a class you have to call parent constructor first
        this.title = title;
        this.pretitle = pretitle;
        this.backgroundImage = backgroundImage;
    }
    [...]
}

According to MDN, When used in a constructor, the super keyword appears alone and must be used before the this keyword is used. The super keyword can also be used to call functions on a parent object. You can read this article, to get better idea.

abby37
  • 597
  • 6
  • 21