返回课程

创建实例时出错

重要性:5

以下是 Rabbit 扩展 Animal 的代码。

不幸的是,无法创建 Rabbit 对象。问题出在哪里?请修复它。

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

这是因为子构造函数必须调用 super()

以下是更正后的代码

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