js super 实现
super 在 JavaScript 中的实现
在 JavaScript 中,super 关键字用于调用父类的构造函数或方法。它主要用于类继承中,确保子类能够正确访问父类的属性和方法。
调用父类构造函数
在子类的构造函数中,super 必须在 this 之前调用,否则会抛出错误。这是因为 super 负责初始化父类的 this 上下文。
class Parent {
constructor(name) {
this.name = name;
}
}
class Child extends Parent {
constructor(name, age) {
super(name); // 调用父类的构造函数
this.age = age;
}
}
const child = new Child('Alice', 10);
console.log(child.name); // 输出: Alice
console.log(child.age); // 输出: 10
调用父类方法
super 也可以用于调用父类的方法,尤其是在子类重写父类方法时。
class Parent {
greet() {
return 'Hello from Parent';
}
}
class Child extends Parent {
greet() {
return super.greet() + ' and Hello from Child';
}
}
const child = new Child();
console.log(child.greet()); // 输出: Hello from Parent and Hello from Child
super 在静态方法中的使用
super 也可以在静态方法中调用父类的静态方法。

class Parent {
static staticMethod() {
return 'Static method from Parent';
}
}
class Child extends Parent {
static staticMethod() {
return super.staticMethod() + ' and Static method from Child';
}
}
console.log(Child.staticMethod()); // 输出: Static method from Parent and Static method from Child
注意事项
super只能在派生类(子类)中使用,否则会抛出语法错误。- 在构造函数中,
super必须在访问this之前调用。 super不能单独使用,必须作为函数调用(如super())或属性访问(如super.method())。
示例:完整的继承链
class GrandParent {
constructor() {
this.family = 'GrandParent';
}
}
class Parent extends GrandParent {
constructor() {
super();
this.parent = 'Parent';
}
}
class Child extends Parent {
constructor() {
super();
this.child = 'Child';
}
}
const child = new Child();
console.log(child.family); // 输出: GrandParent
console.log(child.parent); // 输出: Parent
console.log(child.child); // 输出: Child
通过以上示例和说明,可以清晰地理解 super 在 JavaScript 中的实现和使用方式。






