CodeMasteryLab
Section 11

Object-Oriented JavaScript & Design Patterns

OOP principles in JavaScript, ES6 classes, encapsulation, composition over inheritance, and the most asked design patterns.

OOP JavaScript & Design Patterns

OOP and design patterns are tested in senior interviews and system design rounds.

Four Pillars of OOP in JS

  1. Encapsulation — group data and behavior, hide internals
  2. Abstraction — expose only what's needed
  3. Inheritance — reuse behavior via prototype chain / extends
  4. Polymorphism — same interface, different implementations

Private Fields (ES2022)

class BankAccount {
  #balance = 0; // truly private

  deposit(amount) { this.#balance += amount; }
  get balance() { return this.#balance; }
}

const acc = new BankAccount();
acc.deposit(100);
console.log(acc.balance);  // 100
console.log(acc.#balance); // SyntaxError

Design Patterns

// Singleton
const DB = (function() {
  let instance;
  function createInstance() { return { connection: 'active' }; }
  return {
    getInstance() {
      if (!instance) instance = createInstance();
      return instance;
    }
  };
})();

// Observer
class EventEmitter {
  #listeners = {};
  on(event, cb) { (this.#listeners[event] ??= []).push(cb); }
  emit(event, data) { this.#listeners[event]?.forEach(cb => cb(data)); }
}