Advance JavaScript (DOM, BOM, Web API) / Object Oriented Programming

OOP Introduction

OOP is a programming paradigm centered around objects rather than functions. OOP is not a programming language or tool.


✏️ Four Pillars of OOP

1. Encapsulation

Encapsulation means bundling data (properties) and methods (functions) into a single unit (class/object) and restricting direct access to some of the object’s data.

class BankAccount {
  #balance; // private field

  constructor(owner, balance) {
    this.owner = owner;
    this.#balance = balance;
  }

  // Public method to access private data safely
  getBalance() {
    return `Balance: $${this.#balance}`;
  }

  deposit(amount) {
    if (amount > 0) {
      this.#balance += amount;
      console.log(`Deposited $${amount}`);
    }
  }
}

const account = new BankAccount("Alice", 500);
console.log(account.getBalance()); // ✅ Balance: $500
account.deposit(200);              // ✅ Deposited $200
console.log(account.getBalance()); // ✅ Balance: $700

// console.log(account.#balance); ❌ Error (private field)

✅ Encapsulation hides internal details and provides controlled access.


2. Abstraction

Abstraction means hiding complex implementation details and showing only the necessary features to the user.

class Car {
  startEngine() {
    console.log("Engine started...");
  }

  drive() {
    this.startEngine();  // Abstracted internal step
    console.log("Car is moving...");
  }
}

const myCar = new Car();
myCar.drive();
// Output:
// Engine started...
// Car is moving...

✅ The user only calls drive() without worrying about how startEngine() works internally.


3. Inheritance

Inheritance allows a class (child) to use properties and methods of another class (parent).

class Animal {
  eat() {
    console.log("Eating...");
  }
}

class Dog extends Animal {
  bark() {
    console.log("Woof!");
  }
}

const d = new Dog();
d.eat(); // from Animal
d.bark(); // from Dog

✅ Dog inherits from Animal


4. Polymorphism

Polymorphism means one method behaves differently depending on the object that calls it (many forms).

 class Bird {
  fly() {
    console.log("Bird is flying");
  }
}

class Penguin extends Bird {
  fly() {
    console.log("Penguins can't fly");
  }
}

const b = new Bird();
const p = new Penguin();

b.fly(); // Bird is flying
p.fly(); // Penguins can't fly

✅ Same method → different result.


📌 Quick Summary

  1. Encapsulation → Protects data (private fields, controlled methods).

  2. Abstraction → Shows essential info, hides details (e.g., drive() hides startEngine()).

  3. Inheritance → Reuse properties/methods from parent class (extends).

  4. Polymorphism → Same method works differently in different classes.