You-dont-know-js: Part 3: this & Object Prototypes -> Appendix A: ES6 class -> Class Gotchas

Created on 16 Oct 2016  路  4Comments  路  Source: getify/You-Dont-Know-JS

In the Class Gotchas Section, when I run the code below, I get the following error message:
"Uncaught SyntaxError: 'super' keyword unexpected here"

Why is "super" _not_ expected here?

class P {
foo() { console.log( "P.foo" ); }
}

class C extends P {
foo() {
    super();
}
}

var c1 = new C();
c1.foo(); // "P.foo"

var D = {
foo: function() { console.log( "D.foo" ); }
};

var E = {
foo: C.prototype.foo
};

// Link E to D for delegation
Object.setPrototypeOf( E, D );

E.foo(); // "P.foo"

Most helpful comment

super() is only valid in subclass constructors. in methods, must be super.methodName().

All 4 comments

It's because 'super' - is not a function, but a keyword that helps call methods of object which linked to prototype of the current object.
In this particular case 'super' is used for calling method 'foo' of class P, so it must be super.foo();

You can also call foo function like this: P.prototype.foo.call(this);, but 'super' more beautiful way to do this.

super() is only valid in subclass constructors. in methods, must be super.methodName().

Thank you for your reply.
Is the code below the correct way to use super keyword in the book example?

 class C extends P {
 foo() {
 super.foo();
 }
 }

looks ok

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jorendorff picture jorendorff  路  5Comments

aszx87410 picture aszx87410  路  3Comments

Beaglefoot picture Beaglefoot  路  3Comments

animeshk874 picture animeshk874  路  5Comments

laoshaw picture laoshaw  路  3Comments