js 实现super
实现 super 的功能
在 JavaScript 中,super 关键字用于调用父类的构造函数或方法。可以通过以下方式实现类似 super 的功能:
调用父类的构造函数
在子类的构造函数中,使用 super() 调用父类的构造函数:
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.methodName() 调用父类的方法:
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
使用 Reflect 实现类似功能
如果不使用 class 语法,可以通过 Reflect 和原型链模拟 super 的行为:

function Parent(name) {
this.name = name;
}
Parent.prototype.greet = function() {
return 'Hello from Parent';
};
function Child(name, age) {
Parent.call(this, name); // 类似 super(name)
this.age = age;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.greet = function() {
const parentGreet = Parent.prototype.greet.call(this); // 类似 super.greet()
return parentGreet + ' and Hello from Child';
};
const child = new Child('Alice', 10);
console.log(child.greet()); // 输出: Hello from Parent and Hello from Child
注意事项
super必须在子类的constructor中调用,且必须在this之前调用。- 在方法中使用
super时,确保方法不是箭头函数,因为箭头函数没有自己的super绑定。






