Module pattern vs. instance of an anonymous constructor

Viewed 5581

So there's this so-called module pattern for creating singletons with private members:

var foo = (function () {
    var _foo = 'private!';
    return {
        foo: function () { console.log(_foo); },
        bar: 'public!'
    }
})();

There's also this method that I found on my own, but haven't seen anything written about:

var foo = new function () {
    var _foo = 'private!';
    this.bar = 'public!';
    this.foo = function () { console.log(_foo); };
}

I'm thinking there must be a reason why nobody writes about this while there's tons of articles about the module pattern. Is there any downside to this pattern? Speed, or browser compatibility perhaps?

4 Answers

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.

Related