Let’s Learn ES6: Classes
In this article, we are going to understand one of the most cool features of ES6 which is ES6 classes
In ES5, we were defining class and its methods with three different ways. Here is the overview of it first.
1. Using a Function:
a. Methods defined internally.
b. Methods added to the prototype
2. Using object literals
3. Singleton using a function
It is the combination of first two. Declaration is very similar to 1.a
Now, Back to ES6, ES6 classes are syntactical sugar over the Objects and prototypes that we’re used to working with. They simply offer a much nicer, cleaner syntax for creating these objects and dealing with inheritance.
Notice how elegantly we define property in a constructor like Ruby or Java language. No more function keyword to define function inside it. Functions are defined by putting their name, followed by any arguments within brackets, and then a set of braces. That’s it!! The constructor function is called automatically when an instance of the class is created.
Yes, We can perform inheritance now easily. You have to use just extends keyword. And don’t forget to add super keyword in constructor before using this. Otherwise you will get some error like this :
'this' is not allowed before super()
Here is a simple example of inheritance with a new child class NanoCar which is child of class Car. It has one extra function to check max speed and it uses the function of base class directly.
What if I want to call function of my parent class inside the child class? Here is the way, Super class calls with super.
Here you can see we have used super.getDetails(); which will call getDetails() function of parent class and then store that result in variable details and go ahead for further execution. We can use this approach when we have almost similar methods in child class with parent class and only few changes required. So it will help you not to repeat yourself for same logic which is available in parent class which is the basic goal of inheritance.
That’s it for now. Hope you have enjoyed it. In my next article we will see about some more interesting features of ES6. So keep in touch.
At BoTree Technologies, we build web and mobile applications to add value to our client’s business. We align ourselves to ensure that our client benefits the most out of our engagement.
Drop us a line to discuss how can we help take your business to the next level.
Choose Your Language
- Digital Marketing
- IT Consulting
- Project Management
- Salesforce Development