为什么在原型链上操作 属性 实际上是在对象上创建它?
why manipulating property at prototype chain actually Creates it on object?
我认为证明我所说内容的最佳方式是展示讲述故事本身的代码...
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
对象本身上创建的。
我认为证明我所说内容的最佳方式是展示讲述故事本身的代码...
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
对象本身上创建的。