class is a keyword used for syntax. In other languages, like ruby, we define classes that act as “blueprints” for objects. They serve as templates while objects are instances of those classes. Inheritance of attributes and methods occur through classes.
Here is an example.
In this example we have declared a
Pet object with a constructor method. The constructor method creates object instances with the following attributes:
breed. We then create three objects, or three different pets, by calling the constructor method with
new . To exactly what the first object looks like, we use
console.log(). We then see the following in the browser’s console:
As expected we get back our object that has the appropriate attributes as properties. But at the bottom, we see this
The __proto__ property is a private property that holds a link to another object. That object is referred to as its prototype.Let’s get back to the example and let us expand that property!
When we expand the drop down list, we first see the constructor method that we defined in our
Pet object. This means that this object’s
__proto__ property is linked to the
Pet’s prototype. This is why the object is able to access that constructor method. The Pet prototype object acts a template and allows the
selene object to inherit the constructor method. But what about the second
__proto__ property? Well, let’s expand it!
This time we are given a bigger list! Its seems like the
selene object is linked to the
Pet prototype object,
selene may also access those properties as well. This chain of inheritance is called the prototype chain.
Here is a visual representation of what the chain looks like:
__proto__ property links an object instance with its prototype object. This prototype object allows the inheritance of methods and properties.
selene inherits methods and properties from the
Pet prototype. The
Pet prototype has its own prototype object, which is the global
Object prototype. The
Pet prototype inherits all methods and properties associated with the global
As you can see, our chain ends at the global
Object prototype. This is because the global
Object prototype has no prototype object of its own. This technique of prototype chaining will go on forever until an object has a
Object. This means that the global class
Object will be the final chain in this inheritance chain!
The Differences Between Class and Prototypal Inheritance
- instances inherits from classes(“blueprints”)
- creates a subclass relationship
- instances inherit from other object instances
- allows for selective inheritance
If you are anything like me, you might be overwhelmed with this new information. Here are a list of amazing resources!
- MDN Inheritance and the Prototype Chain
- MDN Object Prototypes
- MDN Article on the