Class

JavaScript class or classes are special functions defined in ES6 version to add more features to JS functional programming. JavaScript Classes are actually extending functionalities of functions in neat and better way with same prototype inheritance model, but using classes, not functions.

Although JS was already using prototype inheritance model using function as object type and their constructors using new keyword. Classes are extending those features and functionalities to avoid confusion between class and functions. Actually in JS Programming language, functions are first class objects. That's why till ES5, Functions were used instead of Classes for constructing objects.

Define function


function Car(name,model,fuel){
    this.name=name;
    this.model=model;
}

instance of function


const swift=new Car('swift','zxi');
const brezza=new Car('brezza','zxi');

Define class

class Car{
    constructor(x,y,z){
        this.name=x;
        this.model=y;
    }
}

instance of class


const swift=new Car('swift','zxi');
const brezza=new Car('brezza','zxi');

The prototype inheritance model is same for both function and classes in javascript.


Define class

JavaScript Classes are defined same like functions, thats why classes are called special functions in javascript. That means, a class can be defined as class declaration and class expression.

Class Declaration


class Car{
    constructor(power,torque){
        this.power=power;        
        this.torque=torque;        
    }
};

const swift=new Car(90,115);

Class Expression


const Car=class{
    constructor(power,torque){
        this.power=power;        
        this.torque=torque;     
    }    
};

const swift=new Car(,90,115);

Class Hoisting

Class declaration or expression is not hoisted. But function declaration is hoisted. This means, we have to define class first, and then use it. Using class name before declaration will throw syntax error in console and block main thread.

Datatype of class

The datatype of class in javascript is function. We can use typeof operator to check datatype of class.


class Car{
    constructor(name,power,torque){
        this.name=name;        
        this.power=power;        
        this.torque=torque;        
    }
}  
   
typeof car;      // "function"         
Car instanceof(Object);      // true         
    


Constructor method

constructor function or method is used in class to declare a object of class. Constructor method can be used only once in a class. Using more than one Constructor method can result in syntax error.


class Car{
    constructor(name,power,torque){
        this.name=name;        
        this.power=power;        
        this.torque=torque;     
    }    
}

let swift=new Car('swift',90,115);
let brezza=new Car('brezza',105,138);

Add custom method

We can add custom methods for new instance in class. See example below.


class Car{
    constructor(power,torque){
        this.power=power;        
        this.torque=torque;     
    } 
    
    // custom method
    start(){
        console.log(`car starts`);
    }
    stop(){
        console.log(`car stopped`);
    }
    
}

let swift=new Car(83,115);

swift.start();                    // "car starts"
swift.stop();                    // "car stopped"

Add getter

we can also add getter method using get keyword. Getter method are get using DOT prefix, but without calling or invoking, like properties.


class Car{
    constructor(power,torque,weight){
        this.power=power;        
        this.torque=torque;     
        this.weight=weight;     
    } 
    
    
    // getter
    get powerToWeight(){
        return this.power/this.weight * 1000;
    }
    get torqueToWeight(){
        return this.torque/this.weight * 1000;
    }  
      
}

let swift=new Car(90,115,875);

swift.powerToWeight;              // 102.85714285714286
swift.torqueToWeight;             // 131.42857142857142


Static properties and methods

To define static properties and methods to class, use static keyword. These properties and methods are restricted to class only, not prototypes.


class Car{
    constructor(power,torque){
        this.power=power;        
        this.torque=torque;     
    }
    
    // static
    static showName="Car";
}

Car.showName;    // Car

Do not use .showName property in any prototype of class, it will return undefined.


Extends Class

The extends keywords is used in class to declare child class or nested class of another class. This is recommended when we have multiple sub classes of a parent class. Like a Car can have different car brands.


class Car{
    constructor(name,power,torque,weight){
            this.name=name;        
            this.power=power;        
            this.torque=torque;     
            this.weight=weight;     
    }
} 

class Maruti extends Car{
    constructor(name,power,torque,weight){
        super(name,power,torque,weight);
    }
}
class Toyota extends Car{
    constructor(name,power,torque,weight){
        super(name,power,torque,weight);
    }
}

const swift=new Maruti("swift",90,113,880);
const brezza=new Maruti("brezza",105,138,1100);

const hyryder=new Toyota("hyryder",115,142,1150);

To call the constructor in subclass, we need super function in child class.


Public and Private fields

Public and Private fields also knows as access modifiers are introduced in class in JavaScript ES2022 ( ECMA 13 ). Public field defines static properties to class. The instance can access these properties. But Private fields are not accessible outside class, means instance cannot use them.

Private fields are now supported in major browsers, but their functionalities differ. Chrome and firefox may show different results. I recommend using Firefox to run code below. Output may differs in Chrome and Edge.

Public and Private Example

3

Error


    class Num{   
        x=3;            // public field
        #y=5;            // private field
                
    } 
        
    const num=new Num();
        
    console.log(num.x);
    console.log(num.#y);

Public Field

In this given example, x, y are public class fields and double is public class method. Public fields are available within class and also accessible to class instance. For example, double can access x value using this.x. But num instance can also access x outside class using num.x.

3

5

6


class Num{   
    x=3;            // public field
    y=5;            // public field

    double(){ return 2 * this.x }
} 

const num=new Num();

console.log(num.x);
console.log(num.y);
console.log(num.double());

Private Field

Private fields are declared using # prefix in class. The value of Private field is only accessible inside class. The instance of class cannot access Private fields.

public methods access private fields. But private methods are not accessible.

3

Error

10

Error


class Num{   
    x=3;            // public field
    #y=5;           // private field

    y1(){ return this.#y*2}
    #y2(){ return this.#y*2}

} 

const num=new Num();

console.log(num.x);             // 3
console.log(num.#y);            // Error
console.log(num.y1());          // 10
console.log(num.#y2());         // Error

Private class field is still misleading in some browsers, like chrome, edge. I recommend using Firefox and Safari to check Private fields.