OOP JavaScript & Design Patterns
OOP and design patterns are tested in senior interviews and system design rounds.
Four Pillars of OOP in JS
- Encapsulation — group data and behavior, hide internals
- Abstraction — expose only what's needed
- Inheritance — reuse behavior via prototype chain / extends
- 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)); }
}