views:

84

answers:

3

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?

A: 

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

Jay
+2  A: 

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.

CMS
A: 

JavaScript is full of hacks. The syntax of new states that an Expression should be after it, so var a = new 1(); is valid (but runtime error).

Here is what I just found out:

js> (new new Function("this.x = 1")).x == 1       
true
js>

The new function() { } is misleading to newbies and regular JS programmers and should not be used unless you must.

SHiNKiROU
There is no `unless you must`. It's just better not to, there's no need for it.
Andy E