torna alle lezioni
Questo materiale è disponibile nelle seguenti lingue: عربي, English, Español, فارسی, Français, Indonesia, 日本語, 한국어, Русский, Türkçe, Українська, 简体中文. Per favore, aiutaci con la traduzione in Italiano.

Error creating an instance

importanza: 5

Here’s the code with Rabbit extending Animal.

Unfortunately, Rabbit objects can’t be created. What’s 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);

That’s because the child constructor must call super().

Here’s 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