I have been studying JS OOP recently, and stopped on the following line (quote):
// these objects do the same
user = {
sayHi: function() {
alert("Hello");
}
};
// method shorthand looks better, right?
user = {
sayHi() { // same as "sayHi: function()"
alert("Hello");
}
};
To tell the truth, the notations are not fully identical. There are subtle differences related to object inheritance (to be covered later), but for now they do not matter. In almost all cases the shorter syntax is preferred.
I haven't found an answer to this question. So, What are the subtle differences between these 2 notations?
My guess is that the quoted text is talking about the fact that a function expression like this cannot use super:
const object = {
toString: function () {
return "Hello World! " + super.toString();
}
};
While the shorthand can use super:
const object = {
toString() {
return "Hello World! " + super.toString();
}
};
console.log(object.toString());
See: MDN Using super.prop in object literals
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