es6 的 class 继承通过 extends 关键字实现,其底层机制依然是基于原型的委托。子类在实例化时,会先调用父类的构造函数来初始化自身属性,并通过 super() 访问父类原型上的方法。

extends 如何建立原型链关系
使用 extends 关键字后,子类的原型对象(prototype)会被设置为父类的一个实例。这意味着子类可以通过原型链直接访问父类原型上定义的方法。同时,子类的构造函数内部必须调用 super(),这相当于调用了父类的构造函数,从而完成属性的初始化。

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;
}
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
super 关键字在不同上下文中的行为
super 关键字在两种主要场景下有不同的含义。在构造函数中,它用于调用父类的构造函数,且必须在 this 被赋值之前调用。在普通方法中,它指向父类的原型对象,允许子类调用或重写父类的方法。
立即学习“Java免费学习笔记(深入)”;

class Parent {
constructor() {
this.value = 10;
}
getValue() {
return this.value;
}
}
class Child extends Parent {
constructor() {
super(); // 必须在此处调用 super()
this.value = 20;
}
getValue() {
return super.getValue() + 5; // 调用父类方法
}
}
const child = new Child();
console.log(child.getValue()); // 25子类实例是否共享父类原型上的静态方法
子类实例不能直接访问父类的静态方法。静态方法是定义在构造函数本身上的,而不是原型链上。虽然子类继承了父类的原型链,但静态方法需要通过子类构造函数本身来调用,而不是通过其实例。


















