According to ES6 shorthand initialiser, following 2 methods are same:
var person = {
name: "Person",
greet: function() {
return "Hello " + this.name;
}
};
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:
let person = {
greet(){
super.greet();
}
};
Object.setPrototypeOf(person, {
greet: function(){ console.log("Prototype method"); }
});
person.greet();
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?
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:
super
.new
.