In JavaScript class
can be defined as a template for making objects. The classes are used for data encapsulation and abstraction. Abstraction is the method of hiding unwanted information from the end-user. Encapsulation is a method to hide the data to protect information to be accessed from outside.
class name {
constructor() {
}
}
The constructor is a special function created at the initialization of a class or making an object of the class. It is mainly used for data initialization. For using objects present inside the class, an object of the class is needed. For making an object the new
keyword is used.
class Name {
}
const nameObject = new Name(); // Class object initialization
Now, let us look at the example of using a class to add two numbers.
class Addition {
constructor (a, b) {
this.a = a;
this.b = b;
}
getAddition() {
return this.a + this.b;
}
}
const addition = new Addition(10, 20);
console.log(addition.getAddition()); // Prints: 30
We can see from the above example, that the value passed through the new Addition(10, 20)
is taken by the constructor and set into the class through the constructor(a, b)
. The getAddition()
, adds the two numbers. The addition
object has access to all the methods present inside the class. So, we call the getAddition()
method and get its return value.