Professional JavaScript: Chapter 3: Prototype and Scope Chains
|
[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:
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:
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:
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.
|
[previous] [next] |
Created: February 2, 2001
Revised: February 2, 2001

Find a programming school near you