Prototype chaining
Let's start with the default way of implementing inheritance - inheritance chaining through the prototype.
As you already know, every function has a prototype
property, which points to an object. When a function is invoked using the new
operator, an object is created and returned. This new object has a secret link to the prototype
object. The secret link (called __proto__
in some environments) allows methods and properties of the prototype
object to be used as if they belonged to the newly created object.
The prototype
object is just a regular object and, therefore, it also has the secret link to its prototype. And so, a chain called a prototype chain is created:
In this illustration, an object A contains a number of properties. One of the properties is the hidden __proto__
property, which points to another object, B. B's __proto__
property points to C. This chain ends with the Object.prototype
object, the grandparent, and every object inherits from it.
This is all good...