loading

ES6 Classes

Classes

ES6 introduced classes.

A class is a form of function, but instead of initiating it with the keyword function, we use the keyword class, and the properties are assigned within the constructor() method.

Example

A simple class constructor:

				
					class Car {
  constructor(name) {
    this.brand = name;
  }
}
				
			

Consider the case of the class name. We started the name “Car” with an uppercase character. This is the normal naming practice for classes.

You can now construct objects using the Car class.

Example

Create an object called “mycar” based on the Car class:

				
					class Car {
  constructor(name) {
    this.brand = name;
  }
}

const mycar = new Car("Ford");
				
			

The constructor function is invoked automatically when the object is created.

Method in Classes

You can add your own methods to a class.

Example

Create a method named “present”:

				
					class Car {
  constructor(name) {
    this.brand = name;
  }
  
  present() {
    return 'I have a ' + this.brand;
  }
}

const mycar = new Car("Ford");
mycar.present();
				
			

As shown in the example above, you call the method by referring to the object’s method name followed by parenthesis (parameters would be inside the parentheses).

Class Inheritance

Use the extends keyword to define a class inheritance hierarchy.

A class formed via class inheritance inherits all of the methods from another class:

Example

Create a class named “Model” which will inherit the methods from the “Car” class:

				
					class Car {
  constructor(name) {
    this.brand = name;
  }

  present() {
    return 'I have a ' + this.brand;
  }
}

class Model extends Car {
  constructor(name, mod) {
    super(name);
    this.model = mod;
  }  
  show() {
      return this.present() + ', it is a ' + this.model
  }
}
const mycar = new Model("Ford", "Mustang");
mycar.show();
				
			

The super() method references the parent class.

By invoking the super() function in the constructor method, we invoke the parent’s constructor method and gain access to its properties and methods.

To learn more about classes, visit our JavaScript Classes section.

Share this Doc

ES6 Classes

Or copy link

Explore Topic