I would highly recommend the object constructor pattern (the first example) over the closure pattern (the second example) for objects you expect a large number of. The constructor pattern will only create one object, an object with a foo property. If you want a method you would then add the method to the constructor prototype:
anObject.prototype.something = function () {
// do something
}
where as using the constructor pattern will allocate at least three objects. Take for example,
function anObject(foo, bar) {
this.something = function () {
// do something
};
}
this will create three objects that are tighly coupled. It will create the object containing a property called something
which then stores a new function object created when anObject
was invoked and, third, it will create the function environment that contains foo
and bar
. This form has the advantage of keeping foo
and bar
inaccessible to anything other than something
but it requires two additional allocations making approximatly three times more expensive than the constuctor pattern, though with modern engine optimizations, your milage may vary. The allocations become worse the more functions you add, adding one additional allocation per function. Using the constructor pattern, the method allocations are shared by each object through the prototype chain and will be much more memory efficient.