3

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?

Alex
  • 51
  • 5
  • 1
    "*object inheritance*"? That's a weird way to put it. They are lacking a `.prototype` and cannot be used with `new`. – Bergi Dec 14 '20 at 20:39
  • 2
    What book/tutorial/course are you reading? Please cite the source of your quote. Also, did you skip ahead to the section where it is actually explained? – Bergi Dec 14 '20 at 20:40
  • Related, if not duplicate: [Why does a method using the shorthand method syntax not contain a prototype object](https://stackoverflow.com/questions/48891399/why-does-a-method-using-the-shorthand-method-syntax-not-contain-a-prototype) – Bergi Dec 14 '20 at 20:43

1 Answers1

4

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

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52