JavaScript

How to Use Class in Node.js

Classes” represent the “OOP(Object Oriented Programming)” concept in the programming languages. These play a key role in sorting the code functionalities and associating them. Moreover, these classes have a clear syntax for creating instances/objects that aid the developers in enhancing the code readability and managing the bulk code in chunks, thereby reducing the code complexity.

Contents Overview

How to Use Class in Node.js?

The class can be used in Node.js using the “class” keyword or within a variable via expression followed by the “curly brackets {}” in which the class members such as methods or constructors are defined.

Why Use Classes in Node.js?

Classes are utilized to create and handle new objects and support the inheritance. Also, these come into effect when there is a need to create objects that store/contain their own data and expose a lot of behavior.

What is a Class Constructor?

A “constructor” is a special method for creating an object/instance associated with the class to invoke its functionalities. This constructor can be parameterized or without parameters. A constructor can also utilize the “super” keyword to invoke the constructor of its parent class in the case of inheritance.

Syntaxes For Class Declaration

The class can be declared using the following two approaches:

  • Class Expression.
  • Directly Using the “class” Keyword.

Syntax(Class Declaration Using Expression)

let classname = class {
 constructor(method1, method2) {
    this.method1 = method1;
    this.method2= method2;
  }};

 

Syntax(Directly Using “class” Keyword)

class classname {
  constructor(method1, method2) {
    this.method1 = method1;
    this.method2= method2;
  }}

 

Example 1: Declaring the Class Using Class Expression

This example declares the class along with the implementation of a parameterized class constructor via expression utilizing a variable:

const sum = class {
constructor(num1, num2) {
   this.num1 = num1;
   this.num2 = num2;
}

add() {
   return this.num1 + this.num2;
}
};
let x = new sum(2,3);
console.log("Sum of Values -> "+x.add());

 

In this code snippet, perform the below-provided steps:

  • Declare the class via expression using the “sum” variable that corresponds to the class name.
  • In its definition, create a parameterized class constructor that sets the values passed as constructor arguments via “this”.
  • Also, define the “add()” function that returns the sum of the passed values.
  • Create a class instance/object via the “new” keyword followed by the “sum()” constructor passing the given values as constructor arguments.
  • Lastly, invoke the “add()” function to add the passed values and return them.

Output

Execute the following cmdlet to run the code:

node index.js

 

Here, it can be analyzed that the addition of the values is retrieved appropriately.

Example 2: Declaring the Class Using the “class” Keyword

In this demonstration, the class can be declared via the conventional “class” keyword approach:

class sum {
 constructor(num1, num2) {
  this.x = num1 + num2;
}};
let y = new sum(2,3).x;
console.log("Sum of Values -> "+y);

 

The code explanation is as follows:

  • Repeat the steps for creating a class and a parameterized class constructor.
  • In the constructor definition, add the passed values via “this” directly.
  • Create a class object and pass the stated values to be added as constructor arguments by referring to “x” and return the sum of values.

Output

Run the below-given cmdlet to execute the code:

node index.js

 

Example 3: Creating User-defined Functions For Retrieving the Values

In this code demonstration, the user-defined functions can be used in the class to return the passed values:

class ID {
    constructor(name, id) {
      this.name = name;
      this.id = id;
    }
    getName() {
      return this.name;
    }
    getID() {
      return this.id;
    }}
  let object = new ID('Harry', 18);
  console.log(object.getName());
  console.log(object.getID());

 

In this snippet of code:

  • Declare the class “ID” and a parameterized constructor that returns the passed values.
  • Now, define the separate functions for each of the passed values named “getName()” and “getID()” to retrieve the passed name and id, respectively.
  • Create a class object having the given values to be passed as constructor arguments.
  • Finally, invoke the “getName()” and “getID()” functions to return the passed values.

Output

Execute the below-given cmdlet to display the passed values:

node index.js

 

Example 4: Applying Class Inheritance in Node.js

This demonstration applies the class inheritance such that a child class inherits the functionalities of the parent class via the “super” keyword:

class Bike {
    constructor(val) {
      this.val = val;
    }
    display() {
      return 'I have a ' + this.val;
    }}
  class Type extends Bike {
    constructor(brand, mod) {
      super(brand);
      this.model = mod;
    }
    out() {
      return this.display() + ', it is a ' + this.model;
    }
  }
  let object = new Type("Honda", "Goldwing");
  console.log(object.out());

 

The code explanation is as follows:

  • Declare the class “Bike” having the stated parameterized constructor to handle the values.
  • Also, create the “display()” function to display the passed values.
  • Now, inherit the child class named “Type” from the parent class “Bike” using the “extends” keyword.
  • Create the child class constructor having the stated parameters that comprise the “super” keyword to invoke the parent class’s constructor and set its value.
  • Also, set the passed constructor’s second parameter i.e., “mod” via “this”.
  • Create the “out()” function and invoke the parent class’s “display()” function in it to display the set value of the parent class constructor via the “super” keyword and the set “mod” value via “this”.
  • Lastly, create a child class object named “object” and pass the given values as its constructor’s arguments.
  • Also, invoke the child class’s “out()” function to display its functionalities along with the parent class’s “display()” function implementation.

Output

The following executed cmdlet runs the code:

node index.js

 

As verified, the inheritance of the functionalities is carried out appropriately.

Example 5: Importing and Exporting the Class in Node.js

This example exports a class defined in a file to another file via the “module.exports” object. This object basically refers to the values to be exported from the particular file:

“index.js” File

Overview of this file that comprises the class functionalities:

let ID = class {
    constructor(name, id) {
      this.name = name;
      this.id = id;
    }
    getName() {
      return this.name;
    }
    getID() {
      return this.id;
    }
  }
  module.exports = ID;

 

In this code:

  • Likewise, define the class named “ID” as an expression.
  • In its definition, similarly, create a parameterized constructor that sets the passed values.
  • Also, define the “getName()” and “getID()” functions to return the passed values.
  • The “exports” object is applied and equals the class i.e., “ID” to export this class.

“template.js” File

In this file, the exported file is imported:

let ID = require('./index.js');
let object = new ID('Liam', 1);
console.log(object.getName());
console.log(object.getID());

 

Here:

  • Import the exported class via “require”.
  • Note: Store the importing statement i.e., “require” in the variable having the same name as the class name.
  • After that, create a class instance, pass the given values as constructor arguments, and invoke the class functions to return the values.

Output

Running the below cmdlet referring to the “template.js” file(in which the class is imported) generates the passed values to the class:

node template.js

 

From this output, it is confirmed that the class is exported and imported appropriately in both files.

Conclusion

The class can be used/declared via the Class expression, or directly using the “class” keyword followed by the curly braces {}. The classes can also be inherited via the “extends” keyword or imported/exported in the files with the help of the “module.exports” object. Moreover, to make use of the class functionalities, its instance is created with the help of the class constructor.

About the author

Umar Hassan

I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.