Javascript class

javascript class

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

Class is a blueprint of an object.

Basic structure of class –


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

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

//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 constructor inside 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 carefull we can’t create multiple constructor 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 must read Javascript class inheritance and Static keyword in javascript article to understand the class concept.

You May Also Like

About the Author: Pankaj Bisht