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
super 也可以用于调用父类的方法。
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 访问父类的静态方法
super 还可以用于调用父类的静态方法。
class Parent {
static getMessage() {
return 'Static message from Parent';
}
}
class Child extends Parent {
static getMessage() {
return `${super.getMessage()} and Child`; // 调用父类的静态方法
}
}
console.log(Child.getMessage()); // 'Static message from Parent and Child'
注意事项
- 在子类的构造函数中,
super()必须在使用this之前调用,否则会抛出错误。 - 如果子类没有定义构造函数,JavaScript 会默认调用
super()。 super只能在类的方法中使用,不能在普通函数中使用。
class Parent {}
class Child extends Parent {
constructor() {
// 如果不调用 super(),会抛出错误
this.name = 'Alice'; // ReferenceError: Must call super constructor in derived class
super();
}
}






