在 javascript 中,使用 class extends 实现继承的核心做法是:在子类的 class 声明后通过 extends 关键字指定父类,并在子类构造函数中使用 super() 调用父类构造函数以完成初始化。这样做能让子类自动获得父类的实例属性和方法,同时支持重写(override)和扩展原有行为。

如何定义一个包含 super() 调用的子类并访问父类方法
定义子类时,必须在 constructor 中显式调用 super(),否则在访问 this 之前会抛出引用错误。调用 super() 会执行父类的构造函数,从而初始化从父类继承来的属性。若需调用父类被重写的方法,可通过 super.methodName() 语法实现。

class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // 必须调用 super()
this.breed = breed;
}
speak() {
super.speak(); // 调用父类方法
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Rex', 'German Shepherd');
dog.speak();
console.log(dog.name); // 继承自 Animal
console.log(dog.breed); // 自有属性运行上述代码将输出:
Rex makes a noise.
Rex barks.
Rex
German Shepherd
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。
立即学习“Java免费学习笔记(深入)”;
静态方法和原型链上的属性如何被继承
静态方法(static)和原型链上的非枚举属性也会随 extends 机制被继承。子类可以直接访问父类的静态方法,且 Object.getPrototypeOf(SubClass) 指向父类构造函数,而 SubClass.prototype.__proto__ 指向 ParentClass.prototype。这种双重继承机制确保了实例方法和静态工具方法的完整传递。

class Calculator {
static add(a, b) {
return a + b;
}
}
class AdvancedCalculator extends Calculator {
static multiply(a, b) {
return a * b;
}
}
console.log(AdvancedCalculator.add(2, 3)); // 5
console.log(AdvancedCalculator.multiply(2, 3)); // 6
console.log(Object.getPrototypeOf(AdvancedCalculator) === Calculator); // true
console.log(AdvancedCalculator.prototype.__proto__ === Calculator.prototype); // true当父类构造函数抛出异常时子类实例化会发生什么
如果父类构造函数在执行过程中抛出异常,super() 调用将中断,导致子类实例无法创建,且 this 未被初始化。此时任何尝试访问 this 的操作都会触发 ReferenceError。开发者应在父类构造函数中加入输入校验或 try-catch 逻辑,以确保继承链的稳定。

















