Professional JavaScript: Chapter 3: Prototype and Scope Chains

1
[previous] [next]

Professional JavaScript

Prototype Chains

Prototype chains allow the JavaScript interpreter to determine whether a property exists for an object or not. Here is a typical object created via a JavaScript constructor:

function Thingy(name) { this.name = name; } Thingy.prototype.color = 'blue'; Thingy.prototype.shape = 'round'; var thing = new Thingy('Jack');

Consider the composition of the thing object. JavaScript objects have properties, and each property can have only one value. If more than one value is required, the property must refer to another object. But hang on a minute. The prototype property for Thingy as declared above has two properties itself – color and shape – so it must refer to another object.

In fact, typeof(Thingy.prototype) reports "object." If the prototype property is an object, it must have its own prototype, assumedly called Thingy.prototype.prototype. What about that object's own prototype? Such behavior could go on forever.

Fortunately, in the normal case the ECMAScript standard says that a constructor function's prototype property is of type Object, and the actual prototype object's own prototype property is null, so there is only one step to the end of the chain. Normally, the only places to look for a property with a given name are directly in the object, and directly in the object's prototype object.

The example above could be re-written to explicitly define the object's prototype, rather than relying on the built-in Object prototype as above. For instance:

function Thingy_common_bits() { this.prototype = null; this.colour = 'blue'; this.shape = 'round'; } function Thingy(name) { this.name = name; } Thingy.prototype = new Thingy_common_bits(); var thing = new Thingy('Jack');

The behavior for the thing object is the same as before. The only difference is that now the prototype property is explicitly set to a new object using an object constructor Thingy_common_bits(). This example could be further changed to show a more general case:

function Thingy_bit1() // prototype constructor { this.prototype = null; this.colour = 'blue'; } function Thingy_bit2() // prototype's prototype constructor { this.shape = 'round'; } function Thingy(name) // object constructor { this.name = name; } Thingy.prototype = new Thingy_bit1(); Thingy_bit1.prototype = new Thingy_bit2(); var thing = new Thingy('Jack'); // object

The thing object still looks the same as the other examples, but this time it is contributed to by two prototype objects, one directly (its own prototype), and one indirectly (its prototype's prototype). This is a prototype chain. If the chain is exhausted without a given property name being found, the property is undefined.

1
[previous] [next]
and
Created: February 2, 2001
Revised: February 2, 2001

URL: http://webreference.com/programming/javascript/advanced/chap3/