SubClasses in Javascript

Below is one of the diagram about which we are talking about from previous blogs.

Till now we have only created objects and made those object inherit properties from its prototypes. We have not achieve the above scenario till now i.e inheritance between classes.

Let’s first look into how we will achieve this in ES5.

Let’s create a function constructor/class Person5

Now let’s create a subclass Athlete5 which will inherit properties of Person5 class.

The first step while creating Athlete5 subclass is that we need to call the super class function constructor as we have done in line no. 25.

Question here is why we have used this keyword inside the call method. The answer to this is near to the reason why we use new keyword. As we create a Athlete empty object, which calls Athlete5 function constructor and set the this keyword to the newly created objects from Athlete5 constructor. this keyword will point to the newly created object.

Now its time to create a Prototype Chain using Obejct.create()

Now the two function constructors are connect. Let’s have a look at them

And yes we are able to see the prototype property of the Person5 function constructor.

Let’s do 1 more exercise. Let’s call calculateAge function and let’s create a function available only for the Athlete5 prototype.

Let’s have a look how we do inheritance in ES6.

Let’s create our super class.

Now let’s create a subclass from this superclass.

The readability is much better in ES6 and it is easier to write. However, if you want to understand how Javascript does all this behind the scenes, then ES5 should be the starting point.

About the author

Deepak Sood

Deepak Sood is Lead Consultant in an IT firm holding expertise in Devops and QA Architecture with 8 years of experience.

His expertise is in building highly scalable frameworks. His skills include Java, Configuration Management, Containers, and Kubernetes.

Reach out to him using contact form.

View all posts