英文:
"SyntaxError: 'super' keyword unexpected here" calling method in ES6 class
问题
class Foo {
go() {
console.log('Foo.go');
}
}
class Bar extends Foo {
go() {
console.log('Bar.go');
super(); // SyntaxError: 'super' keyword unexpected here
}
}
英文:
class Foo {
go() {
console.log('Foo.go');
}
}
class Bar extends Foo {
go() {
console.log('Bar.go');
super(); // SyntaxError: 'super' keyword unexpected here
}
}
I don't understand, this seems as simple as can be. Banged my head against this for an hour.
答案1
得分: 3
在JavaScript中,调用父类构造函数的语法是super()
,但对于所有其他方法,您必须使用语法super.methodName()
。
class Foo {
constructor() {
this.isFoo = true;
}
go() {
this.goFoo = true;
}
}
class Bar extends Foo {
constructor() {
super(); // 这是正确的
this.isBar = true;
}
go() {
super.go(); // 这是正确的
this.goBar = true;
}
}
const o = new Bar;
o.go();
console.log(o);
// Bar {isFoo: true, isBar: true, goFoo: true, goBar: true}
这与Java中的语法相同,但与Ruby不同,Ruby中的super()
始终调用父类中同名的方法。
英文:
In JavaScript invoking the superclass constructor uses the syntax super()
, but
for all other methods you must use the syntax super.methodName()
.
class Foo {
constructor() {
this.isFoo = true;
}
go() {
this.goFoo = true;
}
}
class Bar extends Foo {
constructor() {
super(); // This is correct
this.isBar = true;
}
go() {
super.go(); // This is correct
this.goBar = true;
}
}
const o = new Bar;
o.go();
console.log(o);
// Bar {isFoo: true, isBar: true, goFoo: true, goBar: true}
This is the same syntax as exists in Java, but different from Ruby where super()
always invokes the same-named method in the parent class.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论