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 greet() {
return 'Hello from static Parent';
}
}
class Child extends Parent {
static greet() {
return super.greet() + ' and Hello from static Child';
}
}
console.log(Child.greet()); // 输出: Hello from static Parent and Hello from static Child
注意事项
- 在子类的构造函数中,
super()必须在使用this之前调用。 - 如果子类没有定义构造函数,JavaScript 会默认提供一个构造函数并自动调用
super()。 super只能在类的方法或构造函数中使用,不能在普通函数中使用。
class Parent {
constructor() {
this.name = 'Parent';
}
}
class Child extends Parent {
// 没有定义构造函数,JavaScript 会自动调用 super()
}
const child = new Child();
console.log(child.name); // 输出: Parent
super 的实现原理
super 的实现依赖于 JavaScript 的原型链。当调用 super.method() 时,JavaScript 会从当前对象的原型链上查找 method 方法。
class Parent {
method() {
return 'Parent method';
}
}
class Child extends Parent {
method() {
return super.method();
}
}
const child = new Child();
console.log(child.method()); // 输出: Parent method
箭头函数中的 super
箭头函数没有自己的 super,它会从外层作用域继承 super。
class Parent {
method() {
return 'Parent method';
}
}
class Child extends Parent {
method() {
const arrowFunc = () => super.method();
return arrowFunc();
}
}
const child = new Child();
console.log(child.method()); // 输出: Parent method
总结
super 在 JavaScript 中主要用于:
- 调用父类的构造函数。
- 调用父类的方法(包括静态方法)。
- 确保子类能够正确继承父类的行为。
正确使用 super 是实现类继承的关键部分。







