Classes In Javascript

Classes are one of the biggest addition to ES6. Classes do not add any new functionality to Javascript, they are just a synthetic sugar to the language. They change the way how we do a prototype inheritance in Javascript.

That means classes help in inheritance in creating objects from blueprint. In ES5 we called that blueprint as function constructor.

Let’s write same code in ES5 first.

Here I have written a function constructor in ES5 and created a prototype method calculateAge which is inherited when we create an instance of the function constructor.

From the console we can see that the method calculateAGe is present in the prototype property of the john object.

Let’s now write the same code in ES6

We get the same output. The only difference is that we need to define a constructor and rather than defining a prototype property explicitly, we can just define a method inside the class which will function same as prototype.

One more method that we can define in a class is static methods.

Static Methods are those methods which are just attached to the class and cannot be inherited. We can just call them. This is how static functions look like:

Not inherited

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