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.