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?
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.
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.
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 .
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.
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
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With