What is the difference between defining an object property as a function or already passing the direct parentheses?

Asked

Viewed 36 times

2

What is the difference between store and store2 properties?

const MyObject = {
    store1(req, res) {
       console.log(req, res)
    },
    store2: function(req, res){
       console.log(req, res)
    }
}
  • Hello, Heber! I marked your question as duplicate because it has already been answered here on the site in another question (very similar, inclusive). But in short, between the two you scored, there’s no difference. The first is only syntactic sugar of the second. This new notation was introduced in Ecmascript 2015 (ES6). See indicated response in duplicate message for more details.

  • 1

    @Luizfelipe, test this: console.log(MyObject.store1.hasOwnProperty('prototype'));
console.log(MyObject.store2.hasOwnProperty('prototype'));.I think it’s a peculiarity JS because I could not find documentation on this behavior.

  • 1

    Really interesting, @Augustovasques! I had never tested this (and I ended up noticing another very subtle difference too). I will investigate further because I was curious to understand this behavior. Thank you for pointing out - as always very interesting scores. :)

  • 1

    But it’s funny that: MyObject.store1.__proto__=== MyObject.store2.__proto__ gives true... And although it’s what I really expected, it gets weird (I think) in view of this comment above. I’m trying to find the difference that justifies this... Maybe I’m on the level of spec.

  • 1

    Ah, I did. It’s documented here (must have in the spec also, but I was too lazy to look there :P). Syntactically speaking it’s the same thing (as the above mentioned documentation indicates), but since the new syntax cannot be used as a constructor function, it makes no sense to have the property prototype (which, as we know, is used in the __proto__ instances created by the constructor). cc: @Augustovasques

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.