ES6子类必须在constructor首行调用super()初始化父类,否则无法访问this;super还可用于调用父类方法或静态方法,但受限于作用域和语法约束。

子类通过 super 调用父类的构造函数和方法,是 ES6 类继承的核心机制。必须在子类构造函数中显式调用 super(),否则无法访问 this;而调用父类普通方法时,super 作为对象引用使用。
在子类构造函数中调用父类构造函数
子类构造函数中必须第一行调用 super(...args),把参数传给父类构造函数,完成父类实例初始化。不写或晚于 this 使用会报错。
-
super()必须出现在子类constructor中this之前 - 若父类构造函数需要参数,需原样或加工后传入
super(a, b) - 不写
super()直接用this会抛出ReferenceError
例如:
class Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // ✅ 必须先调用
this.breed = breed; // ✅ 此时 this 已可用
}
}
在子类方法中通过 super 调用父类同名方法
在实例方法或静态方法中,用 super.methodName() 可以调用被重写的父类方法,常用于扩展而非完全覆盖逻辑。
-
super在方法内指向父类的原型(Object.getPrototypeOf(Object.getPrototypeOf(childInstance))) - 只能调用父类的可枚举方法(包括
constructor),不能访问父类私有字段(#field) - 调用时的
this仍指向当前子类实例,所以父类方法里对this的操作会影响子类实例
例如:
class Animal {
speak() {
return `${this.name} makes a sound.`;
}
}
class Dog extends Animal {
speak() {
return super.speak() + ' — Woof!'; // ✅ 复用父逻辑再增强
}
}
new Dog('Leo').speak(); // "Leo makes a sound. — Woof!"
super 在静态方法中的使用
子类静态方法也可用 super 调用父类静态方法,此时 super 指向父类本身(而非原型)。
-
super.staticMethod()等价于ParentClass.staticMethod() - 静态方法中不能访问
this实例属性,但可以访问父类静态属性或调用其静态方法
例如:
class Animal {
static info() {
return 'An animal';
}
}
class Dog extends Animal {
static info() {
return super.info() + ' — and a dog'; // ✅
}
}
Dog.info(); // "An animal — and a dog"
常见错误与注意事项
容易忽略的细节会影响继承行为的正确性:
- 箭头函数中没有自己的
this和super,不能在箭头方法里用super -
super只能在派生类(含extends)中使用,否则报SyntaxError - 不能在
super()前访问this,也不能在调用前对参数做异步处理(如 await) - 若子类没写
constructor,JS 会自动插入constructor(...args) { super(...args); }


















