SyntaxError: super() is only valid in derived class constructors
当 super() 调用在非派生类(使用 extends 关键字的类)的 构造函数 体内使用时,会抛出 JavaScript 异常 "super() 只能在派生类构造函数中调用"。
消息
SyntaxError: 'super' keyword unexpected here (V8-based) SyntaxError: super() is only valid in derived class constructors (Firefox) SyntaxError: super is not valid in this context. (Safari)
错误类型
SyntaxError
哪里出错了?
super() 调用用于调用派生类的基类构造函数,以便基类可以初始化 this 对象。在其他任何地方使用它都没有意义。
super() 也可以在构造函数中嵌套的箭头函数中定义。但是,它不能在其他任何类型的函数中定义。
示例
无效案例
如果类没有 extends 关键字,则不能调用 super(),因为没有基类可供调用。
js
class Base {
constructor() {
super();
}
}
即使类方法是从构造函数中调用的,也不能在类方法中调用 super()。
js
class Base {}
class Derived extends Base {
constructor() {
this.init();
}
init() {
super();
}
}
即使函数用作构造函数,也不能在函数中调用 super()。
js
function Base(x) {
this.x = x;
}
function Derived() {
super(1);
}
Object.setPrototypeOf(Derived.prototype, Base.prototype);
Object.setPrototypeOf(Derived, Base);
有效情况
可以在构造函数中调用任何其他方法之前调用 super()。
js
class Base {}
class Derived extends Base {
constructor() {
super();
this.init();
}
init() {
// …
}
}
可以在构造函数中嵌套的箭头函数中调用 super()。
js
class Base {}
class Derived extends Base {
constructor() {
const init = () => {
super();
};
init();
}
}