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.