How to create a JavaScript class in ES6 ?
A class describes the contents of objects belonging to it: it describes a set of data fields (called instance variables) and it defines the operations on those fields (called methods). You can create a Javascript class by using a predefined keyword named class before the class name. We will show you some examples below to illustrate how it works.
Syntax:
class name { // body of the class }
Creating an object of a class can be accomplished by using the new keyword and calling the constructor of that class. A constructor is declared by using the predefined keyword constructor. Constructors can be of any type, such as default constructors and parameterized constructors. As we can see here, we use a constructor to initialize and declare a variable. However, there can only be one constructor per class, and it can be parameterized or defaulted.
Syntax:
class name { constructor(a, b, c) { // Initialize the class variable } }
Example 1:
HTML
< script > class Geeks { // Constructor constructor(num1, num2) { console.log("Inside Constructor"); // Initialize class variable this.num2 = num2; this.num1 = num1; } } // Initialize the class object let obj = new Geeks(1, 2); console.log(obj.num1); console.log(obj.num2); </ script > |
Output:
Inside Constructor 1 2
Example 2:
HTML
< script > class Geeks { constructor(num1, num2) { this.num2 = num2; this.num1 = num1; } add() { console.log( this.num1 + "+" + this.num2 + "=" + (this.num1 + this.num2)); } } let obj = new Geeks(1, 2); obj.add(); </ script > |
Output:
1+2=3