Object-Oriented Programming (OOP) in JavaScript
Object-Oriented Programming (OOP) is a programming approach where code is structured using objects and classes. It helps in writing modular, reusable, and maintainable code.
The four main principles of OOP are:
Encapsulation
Inheritance
Polymorphism
Abstraction
1. Encapsulation
Encapsulation is the concept of hiding data and controlling access through methods.
class BankAccount {
#balance;
constructor(owner, balance) {
this.owner = owner;
this.#balance = balance;
}
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const acc = new BankAccount("Rahul", 1000);
acc.deposit(500);
console.log(acc.getBalance());
2. Inheritance (Using super)
Inheritance allows one class to reuse properties and methods of another class.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + " makes a sound");
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // calling parent constructor
this.breed = breed;
}
bark() {
console.log(this.name + " barks");
}
}
const dog = new Dog("Tommy", "Labrador");
dog.speak();
dog.bark();
3. Polymorphism
Polymorphism means the same method behaves differently for different objects.
class Animal {
speak() {
console.log("Animal makes sound");
}
}
class Dog extends Animal {
speak() {
console.log("Dog barks");
}
}
class Cat extends Animal {
speak() {
console.log("Cat meows");
}
}
const d = new Dog();
const c = new Cat();
d.speak();
c.speak();
4. Abstraction
Abstraction hides internal implementation and exposes only essential functionality.
class Car {
start() {
this.#checkEngine();
console.log("Car started");
}
#checkEngine() {
console.log("Checking engine...");
}
}
const car = new Car();
car.start();
Static Methods
Static methods belong to the class itself, not to instances.
class MathHelper {
static add(a, b) {
return a + b;
}
}
console.log(MathHelper.add(5, 3));
Conclusion
OOP in JavaScript helps you write clean, structured, and reusable code by organizing logic into classes and objects.
