Javascript - Class Class Expressions

Introduction

Apart from Class declarations, the second way of defining new classes in ES6 is through Class Expressions.

const Circle = class { 
        constructor() { 
                this.radius = 20; 
        } 
} 

Besides variable declarations, these class expressions can also be used to be pass arguments into functions.

function carFactory(car) { 
    return new car(); 
} 

const Toyota  = carFactory(class { 
        start() { 
                console.log("Your car is ready to roll"); 
        } 
        stop() { 
                console.log("Shutting down the engines"); 
        } 
}); 

Toyota.start(); // Your car is ready to roll 

Toyota.stop(); // Shutting down the engines 

In programming languages, if an entity can be

  • passed as an argument,
  • returned from a function,
  • modified, and
  • assigned to a variable,

it is considered to be a first-class citizen of the language.

JavaScript functions is the first-class citizen.

In ES6, classes are also the first-class citizens of the language.

ES6 allows a class to be passed as an argument to functions, and assigned to a variable using class expressions.