New object (function) Javascript vs inline invocation

Are there any considerations to determine which one is best 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 calling a function immediately after defining it?

+7
javascript function private members
source share
3 answers

The new operator calls a function that is called as a constructor function .

I have seen this template before, but I do not see any advantages of using it.

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

I would recommend you stay with the inline invocation template.

+9
source share

If you use functions as event handlers, you might get memory leaks. Look at some articles

+1
source share

This link provides statistics that also confirm that the inline call pattern is larger.

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

+1
source share

All Articles