Prototype
Every object is linked to a prototype object from which it inherits properties.
All objects created from object literals ({}
) are automatically linked to Object.prototype
, which is an object that comes standard with JavaScript.
When a JavaScript interpreter (a module in your browser) tries to find a property, which You want to retrieve, like in the following code:
First, the interpreter looks through every property the object itself has. For example, adult
has only one own property — age
. But besides that one, it actually has a few more properties, which were inherited from Object.prototype.
toString
is an Object.prototype's property, which was inherited. It has a value of a function, which returns a string representation of the object. If you want it to return a more meaningful representation, then you can override it. Simply add a new property to the adult object.
If you call the toString
function now, the interpreter will find the new property in the object itself and stop.
Thus the interpreter retrieves the first property it will find on the way from the object itself and further through its prototype.
To set your own object as a prototype instead of the default Object.prototype, you can invoke Object.create
as follows:
child
's prototype is adult
, whose prototype is Object.prototype
. This sequence of prototypes is called a prototype chain.
Last updated
Was this helpful?