简体   繁体   English

为什么JavaScript原型方法对于同一属性输出不同?

[英]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输出3muffin.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.

相关问题 原型方法中的事件处理函数,为什么认为.keyCode是JavaScript中未定义的属性? - Event Handler function in prototype's method, why does it think .keyCode is a property of undefined in JavaScript? Javascript Prototype重用相同的方法 - Javascript Prototype reuse same method 为什么在javascript中向Array原型添加方法会中断for循环上的迭代? - Why does adding a method to the Array prototype in javascript break iteration on a for loop? Javascript不会调用prototype方法 - Javascript does not call prototype method 为什么内置 Object function 的 `prototype` 字段在 JavaScript 中的处理方式不同? - Why is the `prototype` field of the built-in Object function treated differently in JavaScript? Javascript原型方法“无法设置属性” - Javascript prototype method “Cannot set property” 为什么“ this”和“ prototype”在构造函数与实例上的行为不同? - Why does 'this' and 'prototype' behave differently on constructor vs instance? Javascript中具有“未定义”输出的Array.prototype方法 - Array.prototype method with 'undefined' Output in Javascript 在Javascript中,为什么实例或对象文字没有“原型”属性? - In Javascript, why is there no “prototype” property for an instance or object literal? Javascript:为什么classList不是Element.prototype的属性 - Javascript: Why is classList not a property of Element.prototype
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM