My understanding is all objects of the same type will share the same prototype. So change to the prototype will reflect on every objects. But it seems not the case for property of value type. How is this kind of property stored?
function Person() {
}
Person.prototype.name = "John";
var p1 = new Person();
p1.name = "Luke";
var p2 = new Person();
p2.name = "Mary";
console.log(p1.name); // Luke instead of Mary
console.log(p2.name); // Mary
In case I want to implement a object count of the same type. What's the best way to do it? In other OO language, you normally just use a static member to do it.
Prototype property access is asymmetric.
- Let proto be the value of the [[Prototype]] internal property of O.
- If proto is null, return undefined.
- Return the result of calling the [[GetProperty]] internal method of proto with argument P.
To illutstrate:
var proto = {x:4};
var child = Object.create(proto); // create object with prototype set to `proto`
child.x; // 4, fetched from prototype
child.x = 10;
child.x; // 10, fetched from child
proto.x; // 4, setting on child did not change the prototype
Object.getPrototypeOf(child).x = 6; // you can get around it, and set on the proto.
You can read more about it, and why it works this way in Steve Yegge's excellent "the universal design pattern".