I assume you mean what's the difference between bar
(as you declared it) and
var bar2 = new foo();
There's not a lot of difference between bar
and bar2
, other than that the prototype for bar
will always be the prototype property of Object
(as if you had written var bar = new Object(); bar.something = value; bar.execute = function() {...}
), while the prototype for bar2
will be whatever is assigned to the prototype
property of foo
(or the prototype property of Object
by default).
Other than the issue of prototypes, writing a constructor function is mostly a matter of convenience.
Note that with the constructor approach, you can use the prototype to advantage:
function foo() {
this.something = value;
}
foo.prototype.execute = function() { /* Whatever */ };
Then all instances of foo
share the same execute
function. This is much more space efficient than having a new function object for each foo
object. (Of course, if you're only creating one of these, there's not much advantage.)