Create a JavaScript class

JavaScript is rapidly becoming one of the most popular programming languages. Long gone are the days of just including a portion of JavaScript code to make your web page dynamic. With advancements of the language, a more objected-oriented approach is required. In ECMAScript 6 (or ECMAScript 2015), we are now able to create a JavaScript class using the class keyword.

Before that version of JavaScript was released, you could define a class using a function.

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

You can then instantiate the class and pass in the name and age arguments.

var person = new Person("Bob", 50);

You can use the JavaScript Prototype property and add methods to the existing prototype.

Person.prototype.sayHello = function(){
    alert("Hello, my name is " + this.name);
};

Then you can call the method after class instantiation.

var person = new Person("Bob", 50);
person.sayHello(); // This will alert: Hello, my name is Bob

As mentioned, in ECMAScript 6, classes can now be defined using class, and contain a constructor method.

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

Methods can now be added within the existing class braces.

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  getDimensions() {
    alert('Height: ' + this.height + '. Width: ' + this.width);
  }
}

The instantiation of the class and calling the methods is however the same.

var r = new Rectangle('12', '16');
r.getDimensions(); // This will alert: Height: 12. Width: 16

The extends keyword can be used to create a class as a child of another class, as per this example on the Mozilla website.

The super keyword can be used to call an object’s parent method.

class Rectangle {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }

    getDimensions() {
        alert('Height: ' + this.height + '. Width: ' + this.width);
    }
}

class Square extends Rectangle  {
    getDimensions() {
        alert('The dimensions of a square should be equal.');
        super.getDimensions();
    }
}

var square = new Square(10, 10);
square.getDimensions();

// This will alert:
The dimensions of a square should be equal.
Height: 10. Width: 10

With the ability to define classes using the class keyword and other OOP featured introduced in ECMAScript 6, we can write classes with ease.

With all new features, it is advised to check browser support should you need to use specific functionality from ECMAScript 6.