ποΈ 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.