我正在浏览有关类的 MDN 文档,此处:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
但是在使用示例时注意到,即使我删除了子类中的构造函数,输出也是相同的。我本以为狗的新实例无法将其属性传递给父类(super class),因为它在其类定义中没有使用 super(props)
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
// constructor(name) {
// super(name);
// }
speak() {
console.log(`${this.name} barks.`);
}
}
let d = new Dog('Mitzie');
d.speak(); // "Mitzie barks" even though not calling super class constructor... or are we?!
感谢任何帮助
最佳答案
当您根本没有指定构造函数时,JavaScript 引擎会为您插入一个默认构造函数。在基类中,默认值如下所示:
constructor() {
}
在子类中,它看起来像这样:
constructor(...args) {
super(...args);
}
正如您所看到的,在子类中,默认构造函数将其所有参数传递给父类(super class)构造函数,这解释了 Mitzie 咆哮的原因。 :-)
关于JavaScript子类继承: unexpectedly works even without subclass constructor - why is it needed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57767883/