Open In App

ES6 Classes

There are three concepts in Object-Oriented Programming Object, Class, and Methods. ES6 JavaScript supports Object-Oriented programming components. 

The class contains the Constructors and Functions. The Constructors take responsibility for allocating memory for the objects of the class. The function takes responsibility of the action of the objects. Combing these two Constructor and Functions to make the Class



In the ES6 to create any class, you need to use the class keyword.

Syntax: Declaring Class: 



class Class_name {  
}

Class Expressions: 

var var_name = new Class_name {  
}

The below example will illustrate the ES6 Classes:

Example: This example shows the use of ES6 classes.




class gfg {
 
    // Constructor
    constructor(name, estd, rank) {
        this.n = name;
        this.e = estd;
        this.r = rank;
    }
 
    // Function
    decreaserank() {
        this.r -= 1;
    }
}
const geeks = new gfg("geeks", 2009, 43)
 
geeks.decreaserank();
 
console.log(geeks.r); //Output 42

Output: The example given above declares a class ‘gfg’. The class’s constructor takes three arguments – name, estd, and rank respectively. The ‘this’ keyword refers to the current instance of the class. The geeks() function in the class, print the values of the rank.

42

Class inheritance: The ES6 Class supports the inheritance. Inheritance has the courage to create entities from existing entities. There are two types of Class in ES6: 

Syntax: 

class child_name extends parent_name

Example: This example shows the inheritance in classes. 




class geeks {
    constructor(g) {
        this.Character = g
    }
}
class GeeksforGeeks extends geeks {
    disp() {
        console.log("No of Character:  " + this.Character)
    }
}
var obj = new GeeksforGeeks(13);
obj.disp()

Output: 

No of Character: 13

Inheritance divided into three types: 

class Child extends Root
class Leaf extends Child 
// So the leaf extends root indirectly

Super Keyword: This keyword helps child class to invoke the parent class data. 

super.object

Example: This example shows the use of the super keyword in ES6.




class GeeksforGeeks {
    doPrint() {
        console.log("This doPrint() from Parent called.")
    }
}
class gfg extends GeeksforGeeks {
    doPrint() {
        super.doPrint()
        console.log("This doPrint() is printing a string.")
    }
}
var obj = new gfg()
obj.doPrint()

Output: 

This doPrint() from Parent called.
This doPrint() is printing a string.

Article Tags :