7

Is there any considerations to determine which is better practice for creating an object with private members?

var object = new function () { 
   var private = "private variable";
   return {
       method : function () { 
           ..dosomething with private;
       }
   }
}

VS

var object = function () {
 ...
}();

Basically what is the difference between using NEW here, and just invoking the function immediately after we define it?

Sheldon Ross
  • 5,364
  • 7
  • 31
  • 37
  • [Never ever use `new function(){…}`!](http://stackoverflow.com/a/10406585/1048572) Admittedly, in this particular case where you `return` from the function it's not *that* bad. – Bergi Aug 04 '15 at 19:34

3 Answers3

9

The new operator causes the function to be invoked like a Constructor Function.

I've seen that pattern before, but I don't see any benefits of using it.

The purpose of the new operator is to create an object (the this value inside the constructor), setting the right [[Prototype]] internal property, to build the prototype chain and implement inheritance (you can see the details in the [[Construct]] operation).

I would recommend you to stay with the inline invocation pattern.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • While I agree with CMS because you are using a revealing module pattern and relying on lexical scoping - I would clarify that `new` is appropriate when creating a class-like object built upon a prototype pattern - for example a BackboneJS Model or View. – bjnsn Apr 22 '15 at 17:33
1

This link provides statistics which also confirms that inline invocation pattern is better.

Please note that the measurement is in operations per second which the higher the better

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
1

If you're using functions as event handlers you can get memory leaks. Have a look at some of the articles

Jay
  • 13,803
  • 4
  • 42
  • 69