In our recent posts, we’ve seen how to create objects and how to use object prototyping in creating objects. We’ve seen how to extend objects by adding methods, and how to add them to the right level using prototype.
In this post, you will learn how to use prototypes for basic inheritance. And in the next post, you will learn how you can implement inheritance using the revealing module pattern.
Let’s Start with Prototypes
A prototype is an object from which other objects inherit properties. So each object and be used to prototype other objects.
Since prototypes are themselves objects, every prototype has a prototype too.
Chain of Prototypes
Instead of having a separate instance of a function object for every object, you can make the objects share the method by putting it inside the prototype.
How to Implement Inheritance Using Prototypes
Object.create to inherit. You can also add/override properties as much as you want.
In this example, the getBreed method is shared by rover and spot—until you override the toString method in spot, anyway. After that, spot has its own version of the getBreed method, but the rover object and subsequent objects created with new GreatDane will still share that one instance of the getBreed method defined in the GreatDane.prototype object.