JavaScript Class – Find Out How Classes Works!
Free Web development courses with real-time projects Start Now!!
While programming, we often hear the word Class. This concept is new to JavaScript and provides lots of additional functionality to a JavaScript program. It is a fundamental component of Object-Oriented Programming (OOP). Today this tutorial will help you to understand what JavaScript Class is, and how classes work.
It is important that you understand what JavaScript functions are before you continue this topic. If you mistakenly skipped the topic, go back to DataFlair’s JavaScript Tutorial Series on JavaScript Functions.
If you know what they are and how they work, you are ready to understand the concept of JavaScript Classes.
What is JavaScript Class?
In terms of OOP, we often call classes as a ‘blueprint’ of an object. It determines what the properties of an object are and how it behaves. Classes are not directly used by programs, instead, they create objects that programs use.
JavaScript class, introduced in ECMAScript 2015, are primarily syntactic sugar over JavaScript’s existing prototype-based inheritance.
We will use the Browser Console to check the output this time. It’s a very powerful tool for web development as it simplifies debugging of your code. All the errors and warnings are visible in your Console window. We saw some of the codes in our previous JavaScript tutorials where the output window included the console. To open the browser console in your browser, press Ctrl + Shift + I on your keyboard.
1. How to define a class in JavaScript?
It is a special type of function that is defined with the help of the keyword class instead of function. Similar to functions, the class syntax has two components:
- class declarations
- class expressions
You can declare a JavaScript class in the following manner:
class className{ constructor(parameters){ //properties } //other class methods }
The syntax of class expressions looks like this:
var className = class{ constructor(parameters){ //properties } //other class methods }
Like a function expression, a class expression can be named or anonymous. If named, the name is only visible inside the class expression.
2. Hoisting
There is an important difference between class declarations and function declarations. Function declarations are hoisted while class declarations are not. Thus, you need to define a class before you try to access it. If you don’t, the JavaScript interpreter will throw a ReferenceError.
The new className() creates a new object with all the properties and methods defined in the class. All the properties associated with the objects need to be defined inside the constructor() function. We will discuss this method further in this article. The example below helps us understand the basic concept of a class definition.
Code:
<html> <body> <script> class Shape{ //defining a class constructor(){ //method called automatically document.write("Class <i>Shape</i> created.") this.name = "circle"; this.color = "black"; this.radius = 5; //adding properties } } var shape1 = new Shape(); //creating a new instance of the class </script> </body> </html>
Screenshot:
This program will create a JavaScript object that you can easily understand with the help of the diagram below.
Output:
In the above program, we defined a class Shape with a constructor() function. We instantiated the class i.e. created an object named shape1. The browser window in the output above shows the text we wanted. When we try to access this object in the browser console, it returns the name of the class with all the properties associated with the object.
Great! Now that you understand how to create a class and use it for instantiation, you are ready to learn class methods in a detailed manner.
3. Class Body and Methods
All the code inside the curly brackets { } after the class name (class declaration) or class keyword (class expression) is considered to be the body of that class.
Strict Mode
Strict mode, introduced in ECMAScript5 is a way to add restrictions to JavaScript. The body of the class written in strict mode intentionally has a different syntax than in the non-strict mode. This mode applies to the entire script or an individual function, but not to block statements inside { } brackets.
To invoke strict mode, you need to put the exact statement “use strict”; or ‘use strict’; inside your script. Use it before any other statements in the script (for the whole script) and before any statement in the function body (for the individual function).
Constructor
The constructor method is a unique method available that creates and initializes an object created with the class. Every class always contains a default constructor() that is called when you try to instantiate an object.
A default constructor() method looks something like this:
constructor( ) { }
This method has no parameters or method body. But this method ensures that an object has been created without any properties. When you create your own constructor() method in a class, you override the default method and use that method in your class instead.
But don’t forget, every class can contain only a single constructor() method. If you try otherwise, the browser will throw a SyntaxError.
Prototype Methods: Getters and Setters
Getters and setters define methods on a class that is then used as a class property.
Getters get the function linked to an object property when we attempt to look up the property, using the keyword get. Setters set the function we need to call when we access the object property by binding them together with the keyword set.
The syntax of a getter is as follows:
get getterName( ){ }
The syntax of a setter looks something like this:
set setterName(getterName){ }
These methods help us share the data of our class between different class instances (objects). Let’s understand these terms with the help of a code that experiments with the properties and methods of a circle.
Code:
<html> <body> <h3>DataFlair: Implementing Getters and Setters</h3> <script> class Circle{ //class declaration //constructor method with a single parameter constructor(radius){ this.radius = radius; //setting radius value to object } get area(){ //getter return 3.14*Math.pow(this.radius, 2); //returning area using radius } set area(area){ //setter this.radius = Math.sqrt(area) / 3.14; //returning radius using area } } var circle1 = new Circle(5); //new class instance document.write("Area of circle with radius "+ circle1.radius + " is " + circle1.area + "</br>"); document.write("Radius of circle with area " + circle1.area + " is " + circle1.radius + "</br>"); </script> </body> </html>
Screenshot:
Note: We used two pre-defined methods, pow() and sqrt(), of the Math Object in the program to calculate the square and square root respectively.
Output:
This is a very effective feature of JavaScript that lets you bind an object property and a function together. But be careful when you use getters and setters since the syntax before ECMAScript5 was quite different. We don’t need to study the older format since it is not in much use now. And using the syntax we discussed above is a lot more efficient than any other.
Static Methods
A static method is defined in a class, but it isn’t a part of the object instantiated once it’s created. It doesn’t require any instance and is accessed directly by the class name rather than the object name. The helper methods in utilities will be examples of a static method.
These are the methods that help in the execution of any program. The static methods let us allocate memory to our program and defines various keywords and methods that JavaScript interpreter already understands. The code below shows the working of a static method clearly.
Code:
<html> <body> <script> class tellCourse{ //defining a class constructor(){ //method called automatically this.course = "JavaScript"; //adding course name } normalMsg(){ //class method return "DataFlair says learn " + this.course + " today.</br>"; } static staticMsg(){ //static method return "Which course to choose?</br>" } } var course1 = new tellCourse(); //creating a new instance of the class document.write(tellCourse.staticMsg()); //calling static method document.write(course1.normalMsg()); //calling class method </script> </body> </html>
Screenshot:
Output:
4. Inheritance
Inheritance is an important concept in Object-Oriented Programming. This is a mechanism that allows the child class to acquire all the properties and methods of a parent class (except private properties and methods). We use the keyword extends in a class declaration or a class expression to create a child class of another class.
Note: If there is a constructor present in the subclass, it needs to first call super() before using “this”.
Code:
<html> <body> <script> class Shape{ //defining a class constructor(color){ this.color = color; } msg(){ //parent class method document.write("The color of the shape is " + this.color + "</br>"); } } class Circle extends Shape{ //inheritance constructor(color){ super(color); //using the constructor of parent class to set property } msg(){ //child class method document.write("The color of the circle is " + this.color + "</br>"); } } var c1 = new Circle("Blue"); //creating a new instance of the child class c1.msg(); //calling child method </script> </body> </html>
Screenshot:
Output:
Summary
With this, we come to the end of our tutorial on JavaScript Class. The concept of classes is still new in JavaScript so not many resources are available on them. But hope now you understand exactly what JavaScript Classes are and how they work. We learned different components and methods present inside the body of a class. We also discussed the concept of inheritance in a class. Practice the examples discussed in the tutorial and experiment with the code. See what changes you observe when you alter the code in the browser and share your experience with us.
You must go through with our next article on JavaScript Event Types
Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google