Javascript Classes

Es6 introduce 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 class.
A class describes how to make an object of that class type. Basically class is a blueprint of 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 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

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

Public variable


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

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

Note –

  • Hosting will not work with class keyword

You May Also Like

About the Author: Pankaj Bisht