OneCompiler

JavaScript Classes

JavaScript classes are built on top of constructor functions and prototype. Class is nothing but a blueprint of objects. We need not be duplicate the objects if we have classes available.

Let's see an example of classes


class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    getName() {
        return this.name;
    }
}

To create a new instance of the class ProductDetails we use new keyword.

let person = new Person("Mahav");

Let us compare this with the factory functions.


function Person (name, age){
   this.name = name;
   this.age = age;
}

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

let person = new Person("Madhav", 25);

          (or)
// we can also call function in this way
let person = Person("Madhav",25)

So by the above implementation, we can say that class is just syntactic sugar of the constructor functions.