ECMA - 262 describes prototype chaining as the primary method of inheritance in ECMAScript. The basic idea is to use the concept of prototypes to inherit properties and methods between two reference types. Recall the relationship between constructors, prototypes, and instances: each constructor has a prototype object that points back to the constructor, and instances have an internal pointer to the prototype. What if the prototype were actually an instance of another type? That would mean the prototype itself would have a pointer to a different prototype that, in turn, would have a pointer to another constructor. If that prototype were also an instance of another type, then the pattern would continue, forming a chain between instances and prototypes. This is the basic idea behind prototype chaining.
Implementing prototype chaining involves the following code pattern:
This code defines two types: SuperType and SubType . Each type has a single property and a single method. The main difference between the two is that SubType inherits from SuperType by creating a new instance of SuperType and assigning it to SubType.prototype . This overwrites the original prototype and replaces it with a new object, which means that all properties and methods that typically exist on an instance of SuperType now also exist on SubType.prototype . After the inheritance takes place, a method is assigned to SubType.prototype , adding a new method on top of what was inherited from SuperType.
Instead of using the default prototype of SubType , a new prototype is assigned. That new prototype happens to be an instance of SuperType , so it not only gets the properties and methods of a SuperType instance, but it also points back to the SuperType's prototype. So instance points to SubType.prototype, and SubType.prototype points to SuperType.prototype . Note that the getSuperValue() method remains on the SuperType.prototype object, but property ends up on SubType.prototype . That's because getSuperValue() is a prototype method and property is an instance property. SubType.prototype is now an instance of SuperType , so property is stored there. Also note that instance.constructor points to SuperType because the constructor property on the SubType.prototype was overwritten. Prototype chaining extends to the prototype search mechanism described earlier. As you may recall, when a property is accessed in read mode on an instance, the property is first searched for on the instance. If the property is not found, then the search continues to the prototype. When inheritance has been implemented via prototype chaining, that search can continue up the prototype chain. In the previous example, for instance, a call to instance.getSuperValue() results in a three - step search: 1) the instance; 2) SubType.prototype; and 3) SuperType.prototype , where the method is found. The search for properties and methods always continues until the end of the prototype chain is reached.