SyntaxError: use of super property/member accesses only valid within methods or eval code within methods
当在方法外部使用 super.x 或 super[x] 语法时,会发生 JavaScript 异常“super 属性/成员访问只能在方法或方法内的 eval 代码中使用”。
消息
SyntaxError: 'super' keyword unexpected here (V8-based) SyntaxError: use of super property accesses only valid within methods or eval code within methods (Firefox) SyntaxError: super is not valid in this context. (Safari)
错误类型
SyntaxError
哪里出错了?
super.x 语法用于访问当前对象的原型上的属性。它可以在对象字面量和类的方法、字段初始化器和静态初始化块中使用,但不能在其他上下文中。
示例
无效案例
不能在对象的方法外部使用 super.x
js
const obj = {
__proto__: { x: 1 },
x: super.x, // SyntaxError: use of super property accesses only valid within methods or eval code within methods
};
不能在函数中使用 super.x,即使该函数具有方法的效用
js
function getX() {
return super.x; // SyntaxError: use of super property accesses only valid within methods or eval code within methods
}
const obj = {
getX,
getX2: function () {
return super.x; // SyntaxError: use of super property accesses only valid within methods or eval code within methods
},
};
class Derived extends Base {
getX = () => super.x;
}
有效情况
可以在方法中使用 super.x
js
class Base {
x = 1;
}
class Derived extends Base {
getX() {
return super.x;
}
}
可以在字段初始化器中使用 super.x
js
class Derived extends Base {
x = super.x;
}
也可以在对象方法中使用 super.x
js
const obj = {
__proto__: { x: 1 },
getX() {
return super.x;
},
};