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 test
with this.test
in the first case, JavaScript tries to find the test
in this
(current object). It fails to find it and it goes up the ladder in the prototype chain. It finds test
in the Foo.prototype
and returns that value. That is why you were getting same values for this.test
and Foo.prototype.test
.
Second case:
You were incrementing this.test
. this.test++
can be understood like this
this.test = this.test + 1
Now, it fetches the value of test
from the pototype chain (Foo.prototype.test
will be used, which is 0), adds 1 to it and stores that result in the test
member of the current object. So, you are creating a new member in this
called test
. That is why the value of it is different from Foo.prototype.test
.
You can confirm this by adding one more method, like this
Foo.prototype.deleteTest = function () {
delete this.test;
}
...
...
bar.deleteTest();
bar.getTest('bar');
Now bar.getTest
will print 0
, because we deleted the test
from this
, with deleteTest()
. So, it will go up the ladder and find the test
in Foo.prototype
, which is 0.