Javascript and the Prototype Chain
As we have heard everyone say, almost everything in Javascript is an object. The exceptions are the primitive datatypes (string, number, boolean, symbol, null and undefined). So how can we inherit in Javascript? By using objects. Remember, almost all objects in JS are simply instances of Object
.
All objects have a prototype property. This makes it possible for objects to inherit from other objects. This prototype property is what links one object to another. Through prototype chaining, changes to an object’s prototype can be seen by all objects if they are part of the chain.
In this prototype property, methods and properties are stored for which other objects can inherit from. When a property or method is called, the JS engine begins to locate that property or method. If it is not found, the search will move on and look for it in the object’s prototype. It will continue this cycle until it finds the property it’s looking for. If it can’t find it then the prototype chain eventually ends when an object has null
as it’s prototype (and null
doesn’t have a prototype). This ends the prototype chain.
If we wanted to create an object that inherits from another object, we can utilize the new
keyword. So if an object has a constructor function, we can use new
to instantiate a new instance of that object. When new
is used, a brand new empty object is created. This new object will have its own “internal prototype” property, accessed by calling .__proto__
that is the exact same as the constructor function.
Because we used this
inside the constructor function, any new instance of Athlete
will have these methods since new
binds the properties that are declared with this
to any new object.
We can then add methods to the construction function’s prototype:
And since all instances inherit from Athlete
's prototype, all instances now have access to the run method:
This is all prototypal inheritance. It is simpler than classical inheritance because prototypal only has a single abstraction (objects) while classical inheritance has two abstractions (objects and classes). Prototypal inheritance allows you to create objects from other objects. But classical inheritance is limited to only creating objects from other classes. Both types are useful, but JS is purely prototypal, even though the class
word is being utilized.
You can find me on Github:
https://github.com/dougschallmoser