我认为演示我所说的最好的方法是展示代码本身…
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.
,只是为了完成…如果我做
Cat.prototype.lives = 10;
然后cat1.prototype.lives; // 6
原型链将仅用于解析值。但是当你赋值的时候,属性会在对象上创建。
你可以想到
cat1.lives -= 1;
cat1.lives = cat1.lives - 1;
这里,首先求右边表达式的值。因此,根据原型链,cat1.lives
被分解为7
。但是,当您分配它时,lives
属性是在cat1
对象本身上创建的。