Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between object method and shortened object method syntax in javascript?

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?

like image 403
Alex Avatar asked Feb 25 '26 11:02

Alex


1 Answers

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

like image 63
3limin4t0r Avatar answered Feb 27 '26 00:02

3limin4t0r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!