You're actually asking a couple different questions. So let me concentrate on the first one (modifying the variable names to more easily refer to them and not overwrite Object
):
What exactly is the difference between:
function ObjA() {
this.a = 'text';
}
var objA = new ObjA();
and
function ObjB() {
return {
a: 'text'
};
}
var objB = new ObjB();
The difference is that the former version maintains the prototype chain, whereas the later version discards it. Consider the following lines of code:
ObjA.prototype.b = "something";
ObjB.prototype.b = "something";
The following then becomes true:
objA.b; //is "something"
objB.b; //is undefined
The reason is that the object returned from the "constructor" does not append ObjB's prototype chain. It's a brand new object. So that's the "difference."
The second example (using .prototype
vs. returning an object) actually doesn't really "waste" memory as far as I know (see update). Because the process of calling the new
operator on a function will create a copy of the object's prototype and then call its function. The nice part is that the prototyped methods will be available within the "constructor" function when you use .prototype
, and you'll maintain the prototype chain with that version. But I don't know that there's anything really "wrong" about using the return-based method.
UPDATE:
I checked out the ECMAScript spec on the subject (and oiled my thinking gears a bit) and it appears that I was wrong about the memory wasting. It looks like the methods/properties of the "class" function's prototype property are linked by reference. So it does actually waste a bit of memory to generate a new object rather than making use of the prototype. Additionally, any properties declared in the returned object are instance-level, whereas properties declared in the prototype object are static to the "class" (i.e. shared by all instances).
And as others have noted, your example has a small bug (a
is not available to the prototype object). But that's somewhat immaterial to the question at hand, so I ignored it. (I see you fixed the bug).