Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why property in prototype of an object can not modified by object?

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?

like image 374
ssj Avatar asked Nov 21 '25 12:11

ssj


2 Answers

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.

like image 153
Barmar Avatar answered Nov 24 '25 02:11

Barmar


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.

like image 28
Zakaria Avatar answered Nov 24 '25 03:11

Zakaria



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!