Search code examples
javascriptprototypevalue-type

javascript property of value type in prototype


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.

enter image description here


Solution

  • Prototype property access is asymmetric.

    • When you get a property - if the object does not have it, it will fetch it from the prototype. This is specified as:
    1. Let proto be the value of the [[Prototype]] internal property of O.
    2. If proto is null, return undefined.
    3. Return the result of calling the [[GetProperty]] internal method of proto with argument P.
    • When you set a property - you always set it on the object and not the prototype. As specified here.

    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".