-1

I want to create an object with many instances. What is the difference between making it these two ways?

function anObject(foo,bar){
   this.foo = bar;
   yada yada
};

and this

var anObject = function(foo, bar){
   var foo;
   var bar;
   this.something = function...
}
Jake Stevens
  • 157
  • 4
  • 13
  • 1
    http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname – Rahul R. Feb 26 '13 at 08:42
  • The second one seems invalid. You redeclare an argument as a local variable. At the very least, it's a bad idea. – John Dvorak Feb 26 '13 at 08:43

1 Answers1

0

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.

chuckj
  • 27,773
  • 7
  • 53
  • 49