EngineeringMarch 29, 2024 · 2 min read

OOP in Node.js

JavaScript's object model confuses people arriving from classical OOP languages, and clarity about it pays off directly in code review quality. This is a working tour of OOP in Node.js as it is actually practiced.

This post is part of my Node.js Design Patterns series.

Object-Oriented Programming (OOP) is a widely used programming methodology that enables developers to create programs based on objects and classes. In Node.js, you can apply OOP principles using JavaScript, the primary programming language of Node.js, with core concepts such as classes, objects, inheritance, encapsulation, and polymorphism.

Here’s a basic guide on how to implement OOP in Node.js:

1. Classes and Objects

In JavaScript ES6 and later, the class keyword is used to define a class. A class is a blueprint or template for creating objects.

class Person {     constructor(name, age) {         this.name = name;         this.age = age;     }    greet() {              return `Hello, my name is ${this.name} and I am ${this.age} years old.`;     } } // Creating an object from the Person class const john = new Person('John', 30); console.log(john.greet());

2. Inheritance

Inheritance allows a class to inherit properties and methods from another class. This helps in reusing code and organizing it better.

class Employee extends Person {     constructor(name, age, jobTitle) {         super(name, age); // Calling the parent class constructor         this.jobTitle = jobTitle;     }     introduce() {              return `${this.greet()} I work as a ${this.jobTitle}.`;      .    } } const jane = new Employee('Jane', 28, 'Software Engineer'); console.log(jane.introduce());

3. Encapsulation

Encapsulation is a way to hide the implementation details of a class, allowing access only through public methods. In JavaScript, you can use private variables and methods with the # notation.

class Account {     #balance;     constructor(initialBalance) {             this.#balance = initialBalance;      }      deposit(amount) {              if (amount > 0) {                      this.#balance += amount;                           console.log(`Deposit successful. New balance is: ${this.#balance}`);               }      }      getBalance() {               return this.#balance;      } } const myAccount = new Account(1000); myAccount.deposit(500); console.log(myAccount.getBalance()); // myAccount.#balance; // Error: Private field '#balance' must be declared in an enclosing class

4. Polymorphism

Polymorphism allows subclasses to implement their own versions of methods defined in the parent class.

class Animal {     speak() {         return 'The animal makes a sound.';     } } class Dog extends Animal {     speak() {         return 'Woof! Woof!';     } } const myDog = new Dog(); console.log(myDog.speak()); // Outputs: Woof! Woof!

These examples show how to apply basic OOP concepts in Node.js through JavaScript. These concepts help create applications that are easier to manage, extend, and maintain.

Nguyễn Hải Nam

Nguyễn Hải Nam

Project Management Lead. 16+ years from code to delivery. PMP®. Writing here about project management and engineering.

About me