1

I'm used to create objects in JavaScript using this syntax :

var myObject = new function() {
    this.myMethod = function() {

    }
}

Wich I find more simple to read than the "closure syntax" :

var myObject = (function() {
    return {
       myMethod: function() {

       }
    }
})();

But i've heard that using "new" was a bad thing in JavaScript, and codes i've seen generally use the closure syntax.

Some of you would be able to explain why the closure syntax get over the new syntax ?

Poyoman
  • 1,652
  • 1
  • 20
  • 28
  • 1
    Second approach, also known as *mixin* is the better of both, as per your code. Ideally, Both are equally important. If you have a class and expects to have more than 1 object, you should create a named function and then use `new functionName();` Mixins are considered useful when you have singleton pattern. – Rajesh Jun 07 '17 at 12:41
  • take a look... https://stackoverflow.com/questions/383402/is-javascripts-new-keyword-considered-harmful – F.bernal Jun 07 '17 at 12:45
  • 1
    @Rajesh It's called *module pattern* not *mixin* – Bergi Jun 07 '17 at 12:46
  • 1
    @F.bernal That's not the reason why `new` is considered bad here. – Bergi Jun 07 '17 at 12:47
  • @Bergi my apologies. Will read about it to clarify my understanding. Thanks – Rajesh Jun 07 '17 at 12:49
  • 1
    The first method ads stuff to the prototype chain. and in the second method it doesn't happen so much? the second method helps more with not allowing outside code to not get mixed up within the module pattern – jack blank Jun 07 '17 at 12:50
  • @Bergi ... Sorry it was effectively a duplicated post ... but with this one : https://stackoverflow.com/questions/2274695/new-function-with-lower-case-f-in-javascript ... had some difficulties to find it ... – Poyoman Jun 07 '17 at 13:15

0 Answers0