js 实现super
在 JavaScript 中实现 super 的功能
JavaScript 中的 super 关键字用于调用父类的构造函数或方法。以下是几种常见场景的实现方法:

在构造函数中调用 super
class Parent {
constructor(name) {
this.name = name;
}
}
class Child extends Parent {
constructor(name, age) {
super(name); // 调用父类的constructor
this.age = age;
}
}
const child = new Child('Alice', 10);
console.log(child.name); // 输出: Alice
console.log(child.age); // 输出: 10
在方法中调用父类方法
class Parent {
greet() {
return 'Hello from Parent';
}
}
class Child extends Parent {
greet() {
return super.greet() + ' and Child'; // 调用父类的greet方法
}
}
const child = new Child();
console.log(child.greet()); // 输出: Hello from Parent and Child
在静态方法中使用 super
class Parent {
static staticMethod() {
return 'Static Parent';
}
}
class Child extends Parent {
static staticMethod() {
return super.staticMethod() + ' Static Child';
}
}
console.log(Child.staticMethod()); // 输出: Static Parent Static Child
使用 Reflect 实现类似 super 的功能
const parent = {
greet() {
return 'Hello from Parent';
}
};
const child = {
greet() {
return Reflect.get(parent, 'greet', this)() + ' and Child';
}
};
Object.setPrototypeOf(child, parent);
console.log(child.greet()); // 输出: Hello from Parent and Child
注意事项
super只能在派生类(使用extends的类)中使用- 在构造函数中使用
super必须在访问this之前 - 在普通方法中,
super指向父类的原型对象 - 在静态方法中,
super指向父类本身






