[ Web Proxy ]
URL:
Viewing: https://javascript.info/task/class-constructor-error [Back]  [Original]

Error creating an instance
EN

We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

    Search on Javascript.info:
    Search in the tutorial:
    Light themeDark theme
    DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek
    back to the lesson

    Error creating an instance

    importance: 5

    Heres the code with Rabbit extending Animal.

    Unfortunately, Rabbit objects cant be created. Whats wrong? Fix it.

    class Animal {
    
      constructor(name) {
        this.name = name;
      }
    
    }
    
    class Rabbit extends Animal {
      constructor(name) {
        this.name = name;
        this.created = Date.now();
      }
    }
    
    let rabbit = new Rabbit("White Rabbit"); // Error: this is not defined
    alert(rabbit.name);
    solution

    Thats because the child constructor must call super().

    Heres the corrected code:

    class Animal {
    
      constructor(name) {
        this.name = name;
      }
    
    }
    
    class Rabbit extends Animal {
      constructor(name) {
        super(name);
        this.created = Date.now();
      }
    }
    
    let rabbit = new Rabbit("White Rabbit"); // ok now
    alert(rabbit.name); // White Rabbit

    Web Proxy Viewer  |  New URL  |  Original Page