What exactly is the difference between
function ObjA() {
this.a = 'text';
}
var obj = new ObjA();
and
function ObjB() {
return {
a: 'text'
};
}
var obj = new ObjB();
I’m asking because I was reading this question and I’ve noticed the following in one of the answers:
function Test() {
this.a = 1;
return {
get A() { return this.a; },
set A(v) { this.a = v; }
};
}
so I asked myself what is the difference between that and the following:
function Test() {
this.a = 1;
}
Test.prototype = {
get A() { return this.a; },
set A(v) { this.a = v; }
};
They say in the comments that the former “hogs up memory as the getter and setter is “unique” per each object”. Could someone please elaborate on this?
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:
and
The difference is that the former version maintains the prototype chain, whereas the later version discards it. Consider the following lines of code:
The following then becomes true:
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
.prototypevs. returning an object) actuallydoesn’t really “waste” memory as far as I know(see update). Because the process of calling thenewoperator 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 ((I see you fixed the bug).ais not available to the prototype object). But that’s somewhat immaterial to the question at hand, so I ignored it.