简体   繁体   中英

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 ? Is it simply because fluffy is defined prior to the age change?

I'm extremely new to coding but already have a decent grasp on everything else 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM