1️⃣5️⃣ JavaScript OOP

1️⃣ JavaScript OOP (Overview)

OOP is a way of writing code using objects and classes to organize and reuse logic.

Instead of writing everything in functions, we create blueprints (classes) and objects (instances).


2️⃣ Classes

A class is a blueprint to create objects.

Example:

class Person {
greet() {
console.log("Hello!");
}
}const p1 = new Person();
p1.greet(); // Hello!

👉 Person is a class
👉 p1 is an object (instance)


3️⃣ Constructor

A constructor is a special method that runs automatically when an object is created.

Used to initialize values.

Example:

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
} show() {
console.log(this.name, this.age);
}
}const p1 = new Person("Aditya", 25);
p1.show(); // Aditya 25

👉 this refers to the current object


4️⃣ Inheritance

Inheritance allows one class to reuse properties and methods of another class.

Example:

class Animal {
speak() {
console.log("Animal makes sound");
}
}class Dog extends Animal {
bark() {
console.log("Dog barks");
}
}const d = new Dog();
d.speak(); // inherited
d.bark(); // own method

👉 extends is used for inheritance


5️⃣ Encapsulation

Encapsulation means hiding data and controlling access.

In JavaScript, we use private fields (#).

Example:

class BankAccount {
#balance = 0; // private deposit(amount) {
this.#balance += amount;
} getBalance() {
return this.#balance;
}
}const acc = new BankAccount();
acc.deposit(1000);console.log(acc.getBalance()); // 1000
// console.log(acc.#balance); ❌ Error (private)

👉 Data is protected from direct access


6️⃣ Polymorphism

Polymorphism means same method, different behavior.

Example:

class Animal {
speak() {
console.log("Animal sound");
}
}class Dog extends Animal {
speak() {
console.log("Dog barks");
}
}class Cat extends Animal {
speak() {
console.log("Cat meows");
}
}const animals = [new Dog(), new Cat()];animals.forEach(a => a.speak());

👉 Output:

Dog barks
Cat meows

👉 Same method speak() behaves differently


🔥 Quick Summary

ConceptMeaning
ClassBlueprint for objects
ConstructorInitialize values
InheritanceReuse code from parent class
EncapsulationHide and protect data
PolymorphismSame method, different behavior