Reputation: 4123
Given the following code:
var Test = function() {
var self = this;
var innerPrivate = 1;
self.innerPublic = 1;
self.innerShow = function() {
console.log(innerPrivate++ + ':' + this.innerPublic++);
};
this.constructor.prototype.protoShow = function() {
console.log(innerPrivate++ + ':' + this.innerPublic++);
};
};
var t1 = new Test();
var t2 = new Test();
t2.innerShow(); //1:1
t1.innerShow(); //1:1
t2.innerShow(); //2:2
t1.innerShow(); //2:2
t2.protoShow(); //3:3 (expected: 1:3 or 3:3)
t1.protoShow(); //4:3 (expected: 2:3 or 3:3)
t2.protoShow(); //5:4 (expected: 3:4 or 4:4)
t1.protoShow(); //6:4 (expected: 4:4)
Why is the inner variable both re-used and shared?
Even if the instance is linked to the constructor, the outcome still doesn't seem right.
What am I missing?
Upvotes: 2
Views: 42
Reputation: 67217
Basically prototype is a live connection to the class(function). Whenever you are creating a new instances from the class, those instances will share the prototype properties. The variable innerPrivate
is a closure to both the function inside, but it will be updated with the last instance's variable.
.
.
var t1 = new Test();
var t2 = new Test();
// after execution of the above line
//closure innerPrivate inside of prototype function is replaced with t2's innerPrivate.
//So updating t1's innerPrivate via innerShow of it(t1)
//doesn't affect the closure inside of protoShow
It is always better to avoid altering the prototype inside a constructor. Because doing so will cause unnecessary confusions.
Upvotes: 1