javascript 中 class 语法的继承通过 extends 关键字实现,子类会自动获得父类的属性和方法。在子类的构造函数中必须调用 super() 来执行父类初始化并获取 this 上下文,否则无法访问实例属性。

extends 如何建立原型链关系
extends 关键字不仅复制了方法引用,还建立了原型的继承链,使得 instanceof 检查能够正确识别父子关系。这种机制确保了子类实例可以访问到定义在父类原型上的共享方法,同时保持各自独立的实例状态。

class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a noise.`;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
return `${this.name} barks.`;
}
}
const dog = new Dog('Rex', 'German Shepherd');
console.log(dog.speak()); // Rex barks.
console.log(dog instanceof Animal); // true
console.log(dog instanceof Dog); // true
super() 在构造函数中的具体行为
super() 调用必须在访问 this 之前执行,它负责运行父类的构造函数逻辑并将结果绑定到当前实例。如果省略 super(),子类实例将无法初始化从父类继承的属性,且直接访问 this 会抛出 ReferenceError。

class Parent {
constructor(x) {
this.x = x;
}
}
class Child extends Parent {
constructor(x, y) {
// 必须先调用 super
super(x);
// 此时才能使用 this
this.y = y;
}
}
// const invalid = new Child(1, 2); // 报错: Must call super constructor
const valid = new Child(1, 2);
console.log(valid.x); // 1
console.log(valid.y); // 2
未调用 super() 时的具体错误表现
当子类构造函数中未调用 super() 而尝试访问 this 时,引擎会立即抛出 ReferenceError。这是因为在 ES6 规范中,子类的 this 对象是由 super() 返回的,不调用父类构造器就无法生成这个对象上下文。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











