Skip to content Skip to sidebar Skip to footer

Module Pattern Vs. Instance Of An Anonymous Constructor

So there's this so-called module pattern for creating singletons with private members: var foo = (function () { var _foo = 'private!'; return { foo: function () { c

Solution 1:

In this case it seems you are using only one instance object of that "class". So may want to take look at what Douglas Crockford thinks about putting new directly in front of function:

By using new to invoke the function, the object holds onto a worthless prototype object. That wastes memory with no offsetting advantage. If we do not use the new, we don’t keep the wasted prototype object in the chain. So instead we will invoke the factory function the right way, using ().

So according to the renown javascript architect of Yahoo! you should use the first method, and you have his reasons there.

Solution 2:

More-or-less, they give you the same result. It's just a matter of which path you want to take for it.

The 1st may be more popular since it's simply the mixture of 2 already common patterns:

(function closure() {
    var foo = 'private';
    /* ... */
}())

var singleton = {
    bar : 'public'
};

However, prototype chaining would be the benefit of the 2nd pattern since it has its own constructor.

var singleton = newfunctionSingleton() { };
assert(singleton.constructor !== Object);

singleton.constructor.prototype.foo = 'bar';
assert(singleton.foo === 'bar');

Solution 3:

I don't see any substantial difference between the two. I would prefer the latter simply since it has much less punctuation clutter.

On the other hand the "module pattern" approach seems to be the most common and is becoming a well known pattern (due to the rise in JQuery). It might be better to stick with this recognised pattern not because it has any more technical merit than the other approach but just because it will likely be more recognizable (despite the heavy punctuation).

Solution 4:

Douglas Crockford writes about the second one. As Greg says in his comments, I thought it was quite common, and I've used it in the past.

Edit: to actually answer your question - there's no downsides, the two are functionally equivalent (both create a closure containing the "private variables" and exposing other variables/methods publically), and have exactly the same browser support and performance characteristics. It just comes down to a matter of syntax - basically, where you put the () to actually invoke this function and get your closure, and whether you use the new keyword.

Post a Comment for "Module Pattern Vs. Instance Of An Anonymous Constructor"