DEV Community

Aman Agrawal
Aman Agrawal

Posted on • Originally published at Medium on

Classes in JavaScript

Introduced in ES6, classes are simply the syntactical sugar over function prototyping.

A class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class, and the properties are assigned inside a constructor() method.

Class Basic syntax

Use the keyword class to create a class, and always add the constructor() method. The constructor method is called each time the class object is initialized. After adding a constructor method we can add other methods.

class ClassName {
  // class methods
  constructor() { ... }
  method1() { ... }
  method2() { ... }
  method3() { ... }
  ...
}

Example

A simple class definition for a class named “Product”:

Class Vehicle{
 constructor(brand) {
   this.carname = brand;
 }
}

Now you can create objects using the Vehicle class:

Example

class Vehicle {
  constructor(brand) {
    this.brand = brand;
  }
}
mycar = new Vehicle("Toyota");

Methods

A class in ES6 contains methods for functioning, out of which the constructor method is special, where you initialize properties and called automatically when a class is initiated, and it has to have the exact name “constructor” , in fact, if you do not have a constructor method, JavaScript will add an invisible and empty constructor method.

However we are also free to make our own methods, the syntax should be as below:

class Vehicle {
  constructor(brand) {
    this.brand = brand;
  }
  print() {
    return "I have a vehicle of the brand" + this.brand;
  }
}

mycar = new Vehicle("Toyota");
document.getElementById("demo").innerHTML = mycar.print();

Inheritance

To create a class inheritance, use the extends keyword.

A class created with a class inheritance inherits all the methods from another class:

class Car {
  constructor(brand) {
    this.brand = brand;
  }
  print() {
    return "I have a vehicle of the brand" + this.brand;
  }
}

class Car extends Vehicle {
  constructor(brand, mod) {
    super(brand);
    this.model = mod;
  }
  show() {
    return this.print() + ', it is a ' + this.model;
  }
}

mycar = new Car("Hyundai", "Verna");
document.getElementById("demo").innerHTML = mycar.show();

Important Note :

A common pitfall for novice developers is to put a comma between class methods, which would result in a syntax error.

The notation here is not to be confused with object literals. Within the class, no commas are required.

Top comments (0)