I have the following code:
function Foo() {
Foo.prototype.test = 0;
}
Foo.prototype.incTest = function() {
Foo.prototype.test++;
};
Foo.prototype.getTest = function(name) {
console.log(name +" this: " + this.test + " proto: " + Foo.prototype.test);
};
var bar = new Foo();
var baz = new Foo();
bar.getTest('bar');
bar.incTest();
bar.getTest('bar');
baz.incTest();
bar.getTest('bar');
baz.getTest('baz');
predictably the output is:
bar this: 0 proto: 0
bar this: 1 proto: 1
bar this: 2 proto: 2
baz this: 2 proto: 2
Now I try to take advantage of this looking up the prototype chain, and change incTest to :
Foo.prototype.incTest = function() {
this.test++;
};
This gives me completely different output!
bar this: 0 proto: 0
bar this: 1 proto: 0
bar this: 1 proto: 0
baz this: 1 proto: 0
Shouldn't this.test reference the Foo prototype property? What exactly is going on here?
EDIT:
Furthermore, changing the line to Foo.prototype.test = this.test++; also produces the second output, and I'm not sure why.
EDIT 2:
Solution to first edit was postfix vs. prefix. Prefix increment produces first output.
First case:
You were incrementing only the prototype variable, which will be shared by all the instances of the prototype object.
The important thing to be noted here is, when you access the
testwiththis.testin the first case, JavaScript tries to find thetestinthis(current object). It fails to find it and it goes up the ladder in the prototype chain. It findstestin theFoo.prototypeand returns that value. That is why you were getting same values forthis.testandFoo.prototype.test.Second case:
You were incrementing
this.test.this.test++can be understood like thisNow, it fetches the value of
testfrom the pototype chain (Foo.prototype.testwill be used, which is 0), adds 1 to it and stores that result in thetestmember of the current object. So, you are creating a new member inthiscalledtest. That is why the value of it is different fromFoo.prototype.test.You can confirm this by adding one more method, like this
Now
bar.getTestwill print0, because we deleted thetestfromthis, withdeleteTest(). So, it will go up the ladder and find thetestinFoo.prototype, which is 0.