Prerequisites

Introduction

Inheritance is a key feature of Object-Oriented Programming. Like any other Object-Oriented Programming language, JavaScript also supports inheritance. JavaScript objects have a special hidden property [[ Prototype ]] that is either null or references another object, called "a prototype."

JavaScript Object Reference

Let's understand how this works. When we want to read a property from an object, and it's missing, JavaScript automatically tries to fetch it from its prototype object. In programming, this is called prototype inheritance. In prototype inheritance, the topmost object in the hierarchy chain has its prototype as null. Check the below diagram more clarity.

Prototype Chain

We have talked enough about the property Prototypebut now the question is how can we access this special property? We have a getter/setter for Prototype, i.e. __proto__. Please note that __proto__ is not the same as a prototype, it is just a getter/setter for it. We also have dedicated a getter/setter, Object.getPrototypeOf/Object.setPrototypeOf, that also gets/sets the prototype. Let's check the below code for more clarification.

Initially, the developerobject had only one attribute, i.e code,but after setting its prototype to employee it inherits the workspropertyfrom the employee object.

But, still, we have to confirm whether the works attributegets copied to the developer object or JavaScript internally refers to the employee object for the attribute. We will use hasOwnPropery for validation.

So as we were expecting, when we try to access the property works, it internally refers to the attribute of its Prototype . But still wondering what will happen if we try to write/delete the attribute works of the developer. Let's check.

Lines 12 and 15 confirms that now developer and employee both has its own property works. So we can conclude through this example is that the prototype is only used for reading purposes. Write/delete operation work directly with the Object. Let's verify the same in the console:

In the first part, we discussed how to clone an object using and operator and the Object.assign method. Do you think it will be fine to clone an objectt that has its prototype as another object the same way? Let me know in the comments!

Brain Teaser: Set the prototype of an object to some primitive type and let me know your thoughts in the comments.

Summary

Note: The references can’t go in circles. JavaScript will throw an error if we try to assign __proto__ in a circle. You may find it obvious, but still: there can be only one[[Prototype]]. An object may not inherit from two others.

This was a very brief introduction to inheritance in JavaScript. In Part 3, we will try to understand the keyword this and also look into the constructorfunction.