SmartCodingTips

πŸ—οΈ Real-World OOP in JavaScript

Let’s put Object-Oriented Programming (OOP) into practice by building a basic app using JavaScript classes, inheritance, and encapsulation. We'll simulate a simple **Library System** that lets users borrow books.

πŸ“š Step 1: Define the Book Class

class Book {
  constructor(title, author, available = true) {
    this.title = title;
    this.author = author;
    this.available = available;
  }

  borrow() {
    if (this.available) {
      this.available = false;
      console.log(`${this.title} borrowed.`);
    } else {
      console.log(`${this.title} is not available.`);
    }
  }

  returnBook() {
    this.available = true;
    console.log(`${this.title} returned.`);
  }
}

πŸ‘€ Step 2: Create a User Class

class User {
  constructor(name) {
    this.name = name;
    this.books = [];
  }

  borrowBook(book) {
    if (book.available) {
      book.borrow();
      this.books.push(book);
    } else {
      console.log(`Sorry, ${book.title} is already borrowed.`);
    }
  }

  returnBook(book) {
    const index = this.books.indexOf(book);
    if (index !== -1) {
      book.returnBook();
      this.books.splice(index, 1);
    }
  }
}

πŸ›οΈ Step 3: Setup a Library

const book1 = new Book("The Alchemist", "Paulo Coelho");
const book2 = new Book("1984", "George Orwell");

const user1 = new User("Alice");
user1.borrowBook(book1);  // Alice borrows The Alchemist
user1.borrowBook(book2);  // Alice borrows 1984
user1.returnBook(book1);  // Alice returns The Alchemist

πŸ” Real-World Concepts Used

  • βœ… Classes and Instances
  • βœ… Encapsulation (object state is internal)
  • βœ… Method Encapsulation (borrow/return)
  • βœ… Object Interaction (User borrows Book)
πŸ’‘ Try this: Expand this app by adding a Library class to manage available books and track inventory.