12.1 User Management in a Web Application
Object-oriented programming (OOP) in JavaScript lets you create complex, scalable, and easily maintainable apps. Let's look at some practical examples of using OOP in JavaScript, including classes, inheritance, encapsulation, and polymorphism.
Imagine we're developing a user management web application. We can create classes for different user types, like User, Admin, and Guest, using inheritance to create specialized classes.
Explanation:
- The
Userclass contains methodsloginandlogout - The
Adminclass inherits fromUserand adds the methoddeleteUser - The
Guestclass inherits fromUserand adds the methodrequestAccess - Instances of the
AdminandGuestclasses use their own class methods and those of the base class
Code:
class User {
constructor(username, email) {
this.username = username;
this.email = email;
}
login() {
console.log(`${this.username} logged in.`);
}
logout() {
console.log(`${this.username} logged out.`);
}
}
class Admin extends User {
constructor(username, email) {
super(username, email);
this.role = 'admin';
}
deleteUser(user) {
console.log(`${this.username} deleted user ${user.username}.`);
}
}
class Guest extends User {
constructor(username, email) {
super(username, email);
this.role = 'guest';
}
requestAccess() {
console.log(`${this.username} requested access.`);
}
}
const admin = new Admin('adminUser', 'admin@example.com');
const guest = new Guest('guestUser', 'guest@example.com');
admin.login(); // "adminUser logged in."
admin.deleteUser(guest); // "adminUser deleted user guestUser."
admin.logout(); // "adminUser logged out."
guest.login(); // "guestUser logged in."
guest.requestAccess(); // "guestUser requested access."
guest.logout(); // "guestUser logged out."
12.2 Product Management in an Online Store
In this example, we'll create classes to represent different types of products in an online store, like Product, Electronics, and Clothing. We'll also implement polymorphism for the calculateDiscount method.
Explanation:
- The
Productclass contains acalculateDiscountmethod, which calculates a default 10% discount - The
Electronicsclass overrides thecalculateDiscountmethod, providing a 20% discount for electronics - The
Clothingclass overrides thecalculateDiscountmethod, providing a 15% discount for clothing - Instances of the
ElectronicsandClothingclasses use their owncalculateDiscountmethods to calculate discounts
Code:
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
calculateDiscount() {
return this.price * 0.1; // Default 10% discount
}
display() {
console.log(`${this.name} - $${this.price.toFixed(2)}`);
}
}
class Electronics extends Product {
constructor(name, price, brand) {
super(name, price);
this.brand = brand;
}
calculateDiscount() {
return this.price * 0.2; // 20% discount for electronics
}
}
class Clothing extends Product {
constructor(name, price, size) {
super(name, price);
this.size = size;
}
calculateDiscount() {
return this.price * 0.15; // 15% discount for clothing
}
}
const laptop = new Electronics('Laptop', 1000, 'BrandX');
const tshirt = new Clothing('T-Shirt', 20, 'M');
laptop.display(); // "Laptop - $1000.00"
console.log(`Discount: $${laptop.calculateDiscount().toFixed(2)}`); // "Discount: $200.00"
tshirt.display(); // "T-Shirt - $20.00"
console.log(`Discount: $${tshirt.calculateDiscount().toFixed(2)}`); // "Discount: $3.00"
12.3 Library Management
In this example, we'll create classes for managing a library, including Book, Magazine, and Library classes. We'll also implement methods for adding and removing items from the library.
Explanation:
- The
BookandMagazineclasses inherit from theLibraryItemclass and override thedisplaymethod - The
Libraryclass manages a collection of library items, providingaddItem,removeItem, anddisplayItemsmethods - Instances of the
BookandMagazineclasses are added and removed from the library, and their information is displayed using thedisplaymethod
Code:
class LibraryItem {
constructor(title, year) {
this.title = title;
this.year = year;
}
display() {
console.log(`${this.title} (${this.year})`);
}
}
class Book extends LibraryItem {
constructor(title, year, author) {
super(title, year);
this.author = author;
}
display() {
console.log(`${this.title} by ${this.author} (${this.year})`);
}
}
class Magazine extends LibraryItem {
constructor(title, year, issueNumber) {
super(title, year);
this.issueNumber = issueNumber;
}
display() {
console.log(`${this.title} - Issue ${this.issueNumber} (${this.year})`);
}
}
class Library {
constructor() {
this.items = [];
}
addItem(item) {
this.items.push(item);
console.log(`Added: ${item.title}`);
}
removeItem(title) {
this.items = this.items.filter(item => item.title !== title);
console.log(`Removed: ${title}`);
}
displayItems() {
this.items.forEach(item => item.display());
}
}
const library = new Library();
const book = new Book('JavaScript: The Good Parts', 2008, 'Douglas Crockford');
const magazine = new Magazine('JavaScript Weekly', 2021, 450);
library.addItem(book); // "Added: JavaScript: The Good Parts"
library.addItem(magazine); // "Added: JavaScript Weekly"
library.displayItems();
// "JavaScript: The Good Parts by Douglas Crockford (2008)"
// "JavaScript Weekly - Issue 450 (2021)"
library.removeItem('JavaScript Weekly'); // "Removed: JavaScript Weekly"
library.displayItems(); // "JavaScript: The Good Parts by Douglas Crockford (2008)"
GO TO FULL VERSION