Hello, future developers! π Ever wondered how websites like Amazon manage your shopping cart or how a game like Tic-Tac-Toe keeps track of moves? Itβs all made possible through Object-Oriented Programming (OOP). Donβt worry if youβre new β letβs build up step by step! π
OOP groups data and behavior together into objects, making code reusable, organized, and realistic. Example β your pen, notebook, and laptop each have:
Objects combine these in one unit, just like real-world entities.
JavaScript handles dynamic web elements like buttons, menus, and forms. Each element has:
OOP helps represent them as objects in code for easy control and reusability.
A class is a blueprint. An object is a real item built from that blueprint.
// Class: Recipe (Blueprint)
// Object: The actual cake baked from it
class Car {
constructor(brand, color) {
this.brand = brand;
this.color = color;
}
start() {
console.log(this.brand + " is starting...");
}
}
const car1 = new Car("Tesla", "Red");
car1.start(); // Tesla is starting...
Constructors initialize object properties. They set up initial values when an object is created.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person1 = new Person("Ayush", 25);
console.log(person1.name); // Ayush
Constructors can accept arguments to customize objects.
class Car {
constructor(brand, color) {
this.brand = brand;
this.color = color;
}
}
const car1 = new Car("Toyota", "White");
console.log(car1.color); // White
Just like in Amazon or Flipkart β you add, remove, or clear items from your cart. Here, a ShoppingCart class manages all actions.
const cart = new ShoppingCart();
cart.addItem("Laptop");
cart.addItem("Phone");
cart.viewCart();
Objects β’ Classes β’ Constructors β’ Shopping Cart Demo (Real-World Use Case)
class ShoppingCart {
constructor() {
this.items = new Map();
}
addItem(itemName, quantity = 1) {
const currentQty = this.items.get(itemName) || 0;
this.items.set(itemName, currentQty + quantity);
return `β
${itemName} (x${quantity}) added. Total: ${this.items.get(itemName)}`;
}
removeItem(itemName) {
if (this.items.has(itemName)) {
this.items.delete(itemName);
return `ποΈ ${itemName} removed from the cart.`;
}
return `β οΈ ${itemName} not found in cart.`;
}
viewCart() {
if (this.items.size === 0) return "π Cart is empty.";
return "ποΈ Items in Cart:\n" + Array.from(this.items.entries())
.map(([name, qty]) => `β’ ${name} (x${qty})`).join("\n");
}
clearCart() {
this.items.clear();
return "π§Ή Cart cleared successfully.";
}
}
Output will appear here...