Hello Trailblazers,
Welcome to the sixth tutorial in JavaScript Tutorial Series by SFDC Stop. In this tutorial, we're going to learn about ES6 classes in JavaScript. We'll see how we used to define classes in JavaScript before ES6 and how easy it is to define a class now using ES6 syntax. We'll also learn about defining private variables in JavaScript classes. This tutorial is published on SFDC Stop YouTube Channel. So, if you want to learn in detail, have a look at the tutorial video down below. Otherwise, you can scroll down to have a look at the code gist with explanation.
Tutorial Video
Code Gist with Explanation
How we used to create a class in JavaScript before ES6?
We're going to define a simple class named as Car. The code for the class is given below:
As you can see above, the class car is defined as a function itself because classses in JavaScript are special functions. It will receive two parameters inside the constructor: name and speed, which are parameters to the car function in the code. These two parameters name and speed are used to initialize two data members of the class with the same name i.e. name and speed. Note that the data members are referred by using this keyword.
After the constructor, we have a function named as showSpeed() which is used to display the speed of the car. This function belongs to the Car class, that is why we've used Car.prototype.<function-name> syntax to define the member function. This function can access the data members of the car by using the this keyword.
After the function definition, we simply created the instance of the car class named as audi and passed the name and speed of the car in the constructor as: audi and 200. Finally, we called our showSpeed() method to display the speed of the car by using the class instance. The output when we run this code is given below:
The code is executed successfully and we're getting the expected result i.e. 200 which is the speed of the car.
How can we now define a class in JavaScript using ES6 syntax?
Can we have private variables inside classes in JavaScript?
To summarize, the learnings are given below:-
- Before ES6, we used to define a class by using the syntax of a function because classes in JavaScript are Special Functions. The member functions of the class were defined outside the classs function.
- ES6 made it very simple to define a class using the class keyword. We can define a constructor inside the class as well by using the constructor keyword. The member functions of the class can be defined inside the class body itself.
- We can also define private variables in a class. Private variables must be explicitly declared inside the class body and are prefixed by a #. They can only be accessed inside class member functions.