Ratnesh Lal
Ratnesh Lal

Reputation: 421

super keyword unexpected here

According to ES6 shorthand initialiser, following 2 methods are same:

In ES5

var person = {
  name: "Person",
  greet: function() {
     return "Hello " + this.name;
  }
};

In ES6

var person = {
  name: "Person",
  greet() {
     return "Hello " + this.name;
  }
};

Do the ES6 way is in anyway different from the previous way? If not then using "super" inside them should be also treated as equal, which doesn't hold true, please see below two variaiton:

Below works

let person = {
  greet(){
   super.greet(); 
  }
};

Object.setPrototypeOf(person, {
  greet: function(){ console.log("Prototype method"); }
});

person.greet();

Below fails

let person = {
  greet: function(){
   super.greet(); // Throw error: Uncaught SyntaxError: 'super' keyword unexpected here
  }
};

Object.setPrototypeOf(person, {
  greet: function(){ console.log("Prototype method"); }
});

person.greet();

The only difference in above 2 examples is the way we declare method greet in person object, which should be same. So, why do we get error?

Upvotes: 24

Views: 29249

Answers (3)

yonran
yonran

Reputation: 19134

I got here from searching the V8 error message 'super' keyword unexpected here. Here are the possible reasons for the error:

  • super.prop can only be used in the body of a concise method (foo() {}, *foo() {}, async foo() {}, or async *foo() {}), accessor (get foo() {}, set foo() {}, static get foo(val) {}, or static set foo(val) {}), or constructor() {} (parser-base.h).
    • You can’t access super from an ordinary function foo: function() {} or arrow function foo: () => {}. You must to convert it to a concise function foo() {}.
  • super() call can only be inside a constructor() {} of a derived class (parser-base.h).
    • If you want some method foo() to call the superclass’s foo(), then you call foo() {super.foo()}, not foo() {super()}.
    • Make sure that the class extends some other class.

Upvotes: 2

Sagar Chawla
Sagar Chawla

Reputation: 47

Check the spelling of constructor This error can also occur , If you have a spelling mistake .

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816364

So, why do we get error?

Because super is only valid inside methods. greet: function() {} is a "normal" property/function, not a method, because it doesn't follow the method syntax.

The differences between a method and a normal function definition are:

  • Methods have a "HomeObject" which is what allows them to use super.
  • Methods are not constructable, i.e. they cannot be called with new.
  • The name of a method doesn't become a binding in the method's scope (unlike named function expressions).

Upvotes: 35

Related Questions