JavaScript 中构造函数中 super 怎么调用
在 javascript 的类继承中,super() 用于在子类的构造函数中调用父类的构造函数。它必须在子类构造函数的第一行执行,且只能在 class 定义中使用。调用后,this 对象会被正确初始化,随后才能访问或修改实例属性。

为什么必须在使用 this 之前调用 super
如果在调用 super() 之前使用 this,会抛出 ReferenceError。这是因为子类实例在父类构造函数执行前处于“未初始化”状态,无法安全地访问自身属性。

super() 与直接调用父类构造函数的区别
直接使用 Parent.call(this) 虽然能执行父类逻辑,但不会建立正确的原型链,导致 instanceof 检查失败。而 super() 既执行了父类构造函数,又自动设置了原型链,是标准的继承方式。
立即学习“Java免费学习笔记(深入)”;

class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // 调用父类构造函数
this.breed = breed; // 现在可以安全使用 this
}
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Rex', 'German Shepherd');
dog.speak(); // Rex barks.
console.log(dog instanceof Animal); // true
console.log(dog instanceof Dog); // true


















