Free Web Development Online Tutorials, Learn to Code
javascript class example, javascript classes and objects, javascript class constructor, Inheritance in JavaScript example

JavaScript class Example in ES6

In this tutorial you will learn how to create JavaScript class and object in ES6 syntax, This will surely help you to understand object oriented programming in JavaScript.

JavaScript Classes and Objects

In following example I have created one base class Car and one child class Maruti, the class Maruti is inherited from Car, in base class there is one method checkOil, and we are calling that method from new object of Maruti .

JavaScript class declaration

Notice, how to create constructor in JavaScript class.

class Car {
    constructor(modelName) {
        this.modelName = modelName;
    }
    checkOil() {
        console.log(this.modelName + ' is Checking Oil');
    }
}

constructor() is the place where we can set all default property values, so when any new instance is created, those values will be available to that new instance / object.

In above class "checkOil" is a method inside the "Car" class, we don't need to use function keyword to declare a method inside a class.

Now I am creating the child class "Maruti", will be inherited from above "Car" class

Notice the JavaScript Inheritance example (class Maruti extends Car) using extends keyword

 class Maruti extends Car {
    constructor(model) {
        super(model);
    }
    start() {
        console.log(this.modelName+ ' Starting');
    }
}

Finally creating a new instance of “Maruti” and calling both methods

let mycar = new Maruti("Maruti SX4");
 
mycar.checkOil();
mycar.start();

JavaScript class expressions

We can also define JavaScript class using expression syntax, You don’t need to specify any identifier after class keyword.

Here is an example of class expression in JavaScript.

let Car = class {
    constructor(modelName) {
        this.modelName = modelName;
    }
    checkOil() {
        console.log(this.modelName + ' is Checking Oil');
    }
}
let honda=new Car("Honda");
honda.checkOil();

JavaScript Singleton Pattern

In ES6 we can implement Singleton Pattern, now if you notice at example below, at the time of class declaration I have used a new keyword, and at the end I am passing the model name (parameter value).

let car = new class {
    constructor(model) {
        this.modelName = model;
    }
    start() {
           console.log('Starting '+ this.modelName );
    }
 
}('BMW');
 
car.start(); 

Now while calling the start method of Car class, I can directly call the method without creating any instance again.


ES6 Tutorial | JavaScript Examples