javascript 中继承机制使用 this 先初始化,核心做法是在子类构造函数内部调用 super()。这会触发父类构造函数执行,利用当前实例的 this 完成属性挂载,随后子类才能安全访问 this 并继续初始化自身逻辑。

为什么必须在子类构造器中调用 super
在 ES6 类继承中,子类实例化时不会自动获得父类的 this 上下文。如果不调用 super() 直接操作 this,会抛出 ReferenceError。这是因为 JavaScript 引擎要求子类必须先通过 super() 完成父类构造函数的执行,从而建立完整的原型链和实例状态,之后才允许对 this 进行赋值或读取。

class Animal {
constructor(name) {
this.name = name;
console.log('Animal initialized');
}
}
class Dog extends Animal {
constructor(name, breed) {
// 必须先调用 super() 初始化 this
super(name);
this.breed = breed;
console.log('Dog initialized');
}
}
const myDog = new Dog('Buddy', 'Labrador');
// 输出:
// Animal initialized
// Dog initialized
// myDog.name === 'Buddy'
// myDog.breed === 'Labrador'
super() 参数传递与属性覆盖顺序
super() 的参数直接传递给父类构造函数,决定了父类属性的初始值。如果在子类中再次赋值同名属性,后执行的赋值会覆盖父类设置的值。这种顺序确保了父类逻辑优先执行,子类逻辑随后介入,符合典型的初始化流程。

class Vehicle {
constructor(type) {
this.type = type;
this.status = 'new';
}
}
class Car extends Vehicle {
constructor(model) {
// 传递 'car' 给父类
super('car');
// 子类可以修改父类属性
this.model = model;
this.status = 'ready';
}
}
const myCar = new Car('Sedan');
console.log(myCar.type); // 'car'
console.log(myCar.status); // 'ready' (被覆盖)
console.log(myCar.model); // 'Sedan'
未调用 super 时的具体报错表现
当在子类构造函数中省略 super() 调用而直接尝试访问 this 时,JavaScript 引擎会立即中断执行并抛出 ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor。这一错误明确指出了访问 this 的前提条件尚未满足,强制开发者遵循正确的初始化顺序。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











