ES6 Fundamentals: Classes
In this post of the ES6 Fundamentals blog series, we will learn about the Classes in ES6.
Actually, the concept of Classes is familiar to many programmers from many programming languages like Java, C++ and C# etc and the goal in the JavaScript is the same.
The class keyword creates a class definition and a class definition is a blueprint we can use for creating objects. Creating an object from a class is called instantiating an object form a class.
Well behind the scene, an ES6 class definition is creating a constructor function and manipulating a prototype object. That’s something, we have been doing with JavaScript for years.
This constructor function and prototype setup works but the syntax is hideous because the doesn’t reflect what we want to do in a straightforward manner.
Well, this is where the class keyword in ES6 steps in and you can see the exact same code using the class keyword below:
Defining a Class
JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript’s existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.
Classes are in fact “special functions”, and just as you can define function expressions and function declarations. The class syntax has two components: class expressions and class declarations.
Constructor
Managing state consistently usually requires some initialization logic for an object. We can implement this logic by proving a constructor. Just like the other member of a class, it’s a function that automatically invoked when you execute new keyword with a class name.
Getters and Setters
Once we have some data inside an object, we might want to protect that data. It’s called Encapsulation with getters and setters. Getters and Setters are created using the get and set keywords. They effectively bind a property of an object to a function. So, using getters and setters, we will be writing and reading data using these functions not directly.
Inheritance
Inheritance is one of the three pillars of Object-Oriented Programming i.e. Polymorphism, Encapsulation and Inheritance. ES6 gives us an easy syntax to specify Inheritance relationship. Inheritance is a way of saying that a class inherits from another class, and due to Inheritance that class will have all of the methods and state defined by the other class. Inheritance is achieved in ES6 by extends keyword.
super
There are times when we want to use Inheritance in a certain way where we will want to interact with our super class on a specific way. Infact there may come scenarios where we must want to interact with our super class and in those scenarios, super keyword comes very handy.
Well, it marks the end of this post in the ES6 blog series.
You can find the previous posts here: