JavaScript Classes

Es6 introduces a lot of powerful keywords in javascript and class is one of those powerful keywords. Before es6 in javascript, we didn’t have any keywords to manage the class.
A class describes how to make an object of that class type. So we can say –

Class is a blueprint of an object.

Basic structure of class

ES5 Way


// ES5 
function Student(name) {
    this.name = name;
}

Student.prototype.getName = function() {
    return this.name;
};

var s1 = new Student("John");
s1.getName(); // John

ES6 Way


//ES6
class Student {
    constructor(name) {
        this.name = name;
    }

    getName() {
        return this.name;
    }
}

var s1 = new Student("John");
s1.getName(); // John

Constructor

Now you can see we are using a constructor inside the Student class. It’s called when we created an instance of the object, and memory is allocated for the object.


class Msg {
    constructor() {
        console.log("Welcome inside msg constructor.");
    }
}

var msg = new Msg(); // Welcome inside msg constructor

Constructor overloading in javascript

But Be careful we can’t create multiple constructors in javascript like java.


class Msg {
    constructor() {
        console.log("Welcome inside msg constructor.");
    }
    constructor(name) {
        console.log("Welcome inside msg constructor.", name);
    }
}

var msg = new Msg(); // Uncaught SyntaxError: A class may only have one constructor

Public variable


class Student {
    constructor(name) {
        this.name = name;
    }
}

var s = new Student("XYZ");
s.name; //XYZ

Private variable


class MathsInfo {
    #PI = Math.PI;
    constructor() {
        console.log("Value of PI is :-", this.#PI);
    }
}

var m = new MathsInfo(); // Value of PI is :- 3.141592653589793

Protected variable


class MathsInfo {
    _PI = Math.PI;
    constructor() {
        console.log("Value of PI is :-", this._PI);
    }
}

var m = new MathsInfo(); // Value of PI is :- 3.141592653589793

Note –

  • Hosting will not work with class keyword

You May Also Like

About the Author: Pankaj Bisht