“SyntaxError: ‘super’关键字在此处不被期望” 调用ES6类中的方法

huangapple go评论66阅读模式
英文:

"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.

huangapple
  • 本文由 发表于 2023年2月24日 00:37:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547736.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定