Room51 Technical Documentation

JavaScript Prototypes

Prototype Reference

Each object has a reference to the same prototype object. This is not really inheritance at all. Changing a property of either object's prototype changes the other's because they are one and the same.

The names 'UpChain' and 'DownChain' are not meaningful in this example.


function UpChain() {};
UpChain.prototype.text = "The Same Text";

function DownChain() {};
DownChain.prototype = UpChain.prototype;

var up = new UpChain();
var down = new DownChain();

// Change the DownChain text property
DownChain.prototype.text = "New Text";

Prototype Chain

The prototype of the DownChain object is set to an instance of the UpChain object. Adding properties to the DownChain prototype will simply add properties to the instance of the UpChain object. Those properties are not added to the prototype of the UpChain object, just to the one instance of the object itself.

So, adding properties to DownChain.prototype will affect all instances of DownChain without changing independent instances of UpChain. However, changing UpChain.prototype will affect all instances of UpChain including the instance which is acting as the prototype for all DownChain objects.

Hence, a sort of one way inheritance is achieved.


function UpChain() {};
UpChain.prototype.text = "The Same Text";

function DownChain() {};
DownChain.prototype = new UpChain();

var up = new UpChain();
var down = new DownChain();

// Change the UpChain text property
UpChain.prototype.text = "New UpChain Text";

// Change the DownChain text property
// It will hide UpChain text
DownChain.prototype.text = "New DownChain Text";

// Change the UpChain text property again
// The DownChain text still hides it
UpChain.prototype.text = "Newer UpChain Text";

// Delete the DownChain text property
// The UpChain text will show through
delete(DownChain.prototype.text);

Searching for Properties

Properties aren't really passed down an inheritance hierarchy from top to bottom, they are searched for from bottom to top. As soon as the property is found it is used, even if the same property name occurs further up the chain.

down
(instance of DownChain)
-->DownChain.prototype
(instance of UpChain)
-->UpChain.prototype-->Object.prototype