Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 507
Ratnesh Lal Avatar asked Sep 01 '16 05:09

Ratnesh Lal


People also ask

What is super () in Javascript?

The super keyword is used to access properties on an object literal or class's [[Prototype]], or invoke a superclass's constructor. The super. prop and super[expr] expressions are valid in any method definition in both classes and object literals. The super(... args) expression is valid in class constructors.

What is the use of super keyword?

The super keyword refers to superclass (parent) objects. It is used to call superclass methods, and to access the superclass constructor. The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.

Which statement is true about super () method?

0 super keyword is used to invoke immediate parent class method All the given options are correct super() is used to invoke immediate parent class constructor .

What is super () in angular?

super is ES6 syntax that cannot be used outside the method where it's used. Given there is Foo class that extends Bar , super keyword is interpreted as Bar in Foo constructor and static methods and as Bar.


1 Answers

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).
like image 103
Felix Kling Avatar answered Sep 21 '22 19:09

Felix Kling