OOP in JS (classes, inheritance, polymorphism)
๐น 1. Classes
Section titled โ๐น 1. Classesโ- Classes are blueprint for creating objects. They support constructors, methods and properties.
- Example:
class Person { constructor(name, age){ this.name = name; this.age = age } greet() => { console.log(`My name is ${this.name} and I'm ${this.age} yrs old.`) } }
const person = new Person('Sonam', '26') person.greet() // My name is Sonam and I'm 26 yrs old.๐น 2. Inheritance
Section titled โ๐น 2. Inheritanceโ- One class can extend another, reusing its properties and methods.
- Example:
class Developer extends Person { constructor(name, age, role){ super(name, age) // call parent constructor this.role = role } code(){ console.log(`${this.name} is coding as a ${this.role}`) } }
const dev = new Developer('Sonam', 26, 'Full Stack Developer') dev.code() // Sonam is coding as a Full Stack Developer๐น 3. Polymorphism
Section titled โ๐น 3. Polymorphismโ- Methods can be overriden in child classes to provide specialized behaviour.
- Example:
class Animal { speak() { console.log("The animal makes a sound."); } }
class Dog extends Animal { speak() { console.log("๐ถ The dog barks."); } }
class Cat extends Animal { speak() { console.log("๐ฑ The cat meows."); } }
const animals = [new Dog(), new Cat(), new Animal()]; animals.forEach(a => a.speak()); // ๐ถ The dog barks. // ๐ฑ The cat meows. // The animal makes a sound.๐น 4. Encapsulation
Section titled โ๐น 4. Encapsulationโ-
๐ Hiding internal details and exposing only whatโs necessary.
-
Achieved using class fields (
#private) and getter/setter methods. -
Eg:
class BankAccount {#balance = 0; // private propertydeposit(amount) {if (amount > 0) this.#balance += amount;}withdraw(amount) {if (amount <= this.#balance) this.#balance -= amount;else console.log("Insufficient balance");}get balance() { // getterreturn this.#balance;}}const acc = new BankAccount();acc.deposit(100);acc.withdraw(50);console.log(acc.balance); // 50// console.log(acc.#balance); โ Error (private) -
โ Keeps sensitive data safe and controlled.
-
๐น 5. Abstraction
Section titled โ๐น 5. Abstractionโ-
๐ Hiding complex implementation and showing only the essential functionality.
- In JS, done via abstract-like base classes or interfaces (TS).
- Eg:
class Vehicle {startEngine() {throw new Error("startEngine() must be implemented");}}class Car extends Vehicle {startEngine() {console.log("๐ Car engine started");}}const c = new Car();c.startEngine(); // ๐ Car engine started- โ Forces subclasses to implement required methods, hiding complexity.
๐ฏ Summary Table
Section titled โ๐ฏ Summary Tableโ| Pillar | Meaning | Example in JS |
|---|---|---|
| Encapsulation | Hide internal details | Private fields #balance |
| Abstraction | Show only essentials | Abstract base Vehicle |
| Inheritance | Reuse functionality | class Dog extends Animal |
| Polymorphism | Same method, different behavior | speak() in Dog/Cat/Bird |
๐น Summary
Section titled โ๐น Summaryโ- Class -> Blueprint for object.
- Inheritance -> Reuse properties/methods via
extends - Polymorphism -> Same method, different behaviour in subclasses.
๐ In real-world JS/TS (Node.js, React):
Section titled โ๐ In real-world JS/TS (Node.js, React):โ- Classes are used for models (like
User,Product). - Inheritance for specialized classes (like
AdminUserextendsUser). - Polymorphism for overriding behavior (like
render()in React components). - Encapsulation โ Hide DB logic inside classes (e.g.,
UserModel). - Abstraction โ Base service classes, interfaces.