Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ecmascript 6 - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...