Reputation: 18097
I think best way to demonstrate what i am saying is show the code that tells the story itself...
function Animal() {this.lives=7;}
function Cat() {}
Cat.prototype = new Animal();
cat1 = new Cat();
for (var i in cat1) { if (cat1.hasOwnProperty(i)) { console.log(i);}}
//undefined --as expected since property lives exists in prototype chain, Cat.prototype.
//but when i do this
cat1.lives -= 1;
// and now if i run this again
for (var i in cat1) { if (cat1.hasOwnProperty(i)) { console.log(i);}}
// lives -- How?? I just manipulated property in proto chain i didnt do obj.val = 3; which would create a new property.
and just to be complete.. if i do
Cat.prototype.lives = 10;
then
cat1.prototype.lives; // 6
Upvotes: 2
Views: 36
Reputation: 239523
The prototype chain will be used only for resolving the value. But when you are assigning something, then the property will be created on the object.
You can think of
cat1.lives -= 1;
as
cat1.lives = cat1.lives - 1;
And here, first the right hand side expression is evaluated. So, cat1.lives
is resolved to be 7
, as per the prototype chain. But, when you are assigning it, the lives
property is created on the cat1
object itself.
Upvotes: 3