Rashi Chouksey

JavaScript ES6 classes

ES6 introduced classes in JavaScript. Classes are just the templates for the object in JavaScript.

Class Declaration

Classes in javascript are basically template for the creating object that means you can create multiple objects after creating template for example:

class Animal {
    constructor(type,breed,color){
        this.type= type;
        this.breed = breed;
        this.color = color;
    }
}


typeof Animal
'function'

Note: If you like to known the type of the class you can check the type of function of the javascript

/* objects creation */
const Dog = new Animal("Dog","German","Black");
Dog.breed
'German'
Dog.color
'Black'
Dog.type
'Dog'

Class Methods

/* this is the template */

class Animal {
    constructor(type,breed,color){
        this.type= type;
        this.breed = breed;
        this.color = color;
    }
changeColor(color) {
	this.color = color;
  }
}

/* objects creation */

const Dog = new Animal("Dog","German","Black");
Dog.changeColor("Grey");
Dog.color
'Grey'

Static methods

Static before any method of the class bound it to the respective class that means any instance from that class can not used that method.

class Animal {
    constructor(type,breed,color){
        this.type= type;
        this.breed = breed;
        this.color = color;
    }
 changeColor(color) {
	this.color = color;
  }
static changeType(typeValue) {
	this.type = typeValue;
 }
}

/* output */

const Dog = new Animal("Dog","GSD","brown");
Dog.changeType("Cat");
VM416:1 Uncaught TypeError: Dog.changeType is not a function
    at <anonymous>:1:5

When an instance tries to access the static type method it throws an error.

Extends keyword

Using extends keyword javascript provides the inheritance property to the class. It helps to pass the parent class property to the child class for example:

/* extending Animal class */

class Aquatic extends Animal {
     
    constructor(type,breed,color,waterType) {
        super(type,breed,color);
        this.waterType = waterType;
    }
}

Note: always call super inside child class to inherit parent class property.

/* creating instance from child class */

const Fish = new Aquatic("Whale","Large","Blue","Salt water");


/* output */ 

Fish.breed
'Large'
Fish.type
'Whale'
Fish.color
'Blue'
Fish.waterType
'Salt water'
Share