Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript new object (function ) vs inline invocation

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?

like image 584
Sheldon Ross Avatar asked Apr 05 '10 22:04

Sheldon Ross


3 Answers

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.

like image 130
Christian C. Salvadó Avatar answered Nov 10 '22 17:11

Christian C. Salvadó


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

like image 21
Jay Avatar answered Nov 10 '22 18:11

Jay


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

like image 22
Max Koretskyi Avatar answered Nov 10 '22 17:11

Max Koretskyi