I'm using a bit of code that I found on the web to manufacture objects. It allows me to organize objects into namespaces, and keeps my code pretty readable.
var TEST = {};
//The next two lines is the stuff that I found on the web. I think I
//basically understand what's going on here, but maybe I'm implementing it
//incorrectly?
TEST.testObj = function () { this.initialize.apply(this, arguments); };
TEST.testObj.prototype = {
a: null,
b: [],
initialize: function(a) {
this.a = a;
this.b[0] = a;
}
}
t1 = new TEST.testObj(1);
t2 = new TEST.testObj(2);
alert(t1.a + ', ' + t2.a);
alert(t1.b + ', ' + t2.b);
So, basically t1.a, a primitive, retains it's value when t2 is instantiated. But t1.b changes. It seems like both instances are simply referencing a single array, but creating unique primitives.
If you are fuzzy about prototype inheritance, make sure you read up on it - it will help you reason about this problem. In essence, an object inherits all properties of its prototype, but an object's own properties has higher precedence than those of its prototype. In your example,
TEST.testObj.prototypeis the prototype of botht1andt2. Thus, botht1andt2inherit its properties.When the
Test.testObjconstructor is called, it then calls theinitializemethod, which then sets the object'saproperty to the passed-in parameter. This operation will create anaproperty on the object itself (it's own property), this will override the inheritedaproperty onTest.testObj.prototype. Thus, each time a constructor is called, the new object will get its ownaproperty.The second statement in
initializeis different in nature. It first looks up property
bon the object. Since it is not found on the object itself, it goes up to its prototypeTest.testObject.prototypeand finds it there. Now, having a handle on the array object, it then modifies its zeroth element. As you can see, each time the constructor gets called, this same array will be modified.