When I execute the following js code, I found something weird:
function Contact(name, email) {
this.name = name;
this.email = email;
}
Contact.prototype = {
a: 10,
b: 20
};
var obj = new Contact('ssj', 'ssh');
obj.a = 'ssjssh';
console.log(obj);
console.log(Contact.prototype);
//output: { name: 'ssj', email: 'ssh', a: 'ssjssh' },{ a: 10, b: 20 }
so my question is that why obj.a = 'ssjssh' only add a property in obj, instead of change the property a in Contact.prototype?
Properties in the prototype are only used as a default when reading them. This allows all the members of a class to get the same initial or default values for properties. But each object can override these default properties by having its own values. When you assign to the property, it always goes to the object's own properties, otherwise there wouldn't be any way to override the defaults.
From Eloquent Javascript by Marijn Haverbeke :
When you add a property to an object, whether it is present in the prototype or not, the property is added to the object itself, which will henceforth have it as its own property. If there is a property by the same name in the proto- type, this property will no longer affect the object. The prototype itself is not changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With