[英]Why does JavaScript prototype method output differently for the same property?
Can someone explain to me like I lack basic brain function why fluffy.age
outputs 3
while muffin.age
outputs 4
? 有人可以像我缺乏基本的大脑功能那样向我解释为什么
fluffy.age
输出3
而muffin.age
输出4
吗? Is it simply because fluffy
is defined prior to the age change? 是否仅仅是因为在年龄变化之前就定义了
fluffy
度?
I'm extremely new to coding but already have a decent grasp on everything else JavaScript; 我对编码非常陌生,但是对其他所有JavaScript都有相当的了解。 However, the prototype idea still makes little sense to me.
但是,原型的想法对我来说仍然毫无意义。
function Cat(name, color, meow) { this.name = name; this.color = color; } Cat.prototype.age = 3; var fluffy = new Cat("Fluffy", "White"); console.log(fluffy.age); Cat.prototype = { age: 4 }; console.log(fluffy.age); var muffin = new Cat("Muffin", "Brown"); console.log(muffin.age);
You are updating the prototype after you created an instance from that. 从中创建实例后,您将更新原型。 So that instance does not contain updated prototype properties.
因此,该实例不包含更新的原型属性。
function Cat(name, color, meow) { this.name = name; this.color = color; } Cat.prototype.age = 3; var fluffy = new Cat("Fluffy", "White"); console.log('Before update', fluffy.age); fluffy.age = 4; console.log('After update', fluffy.age); var muffin = new Cat("Muffin", "Brown"); console.log('New object', muffin.age);
When you create a new instance from a class and if you want to change the values in that instance, you need to use that instance not the original class 从类创建新实例时,如果要更改该实例中的值,则需要使用该实例而不是原始类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.