12.1 Quản lý người dùng trong ứng dụng web
Lập trình hướng đối tượng (OOP) trong JavaScript cho phép tạo ra các ứng dụng phức tạp, dễ mở rộng và dễ bảo trì. Hãy cùng xem một vài ví dụ thực hành về việc sử dụng OOP trong JavaScript, bao gồm classes, kế thừa, đóng gói và đa hình.
Giả sử chúng ta đang phát triển một ứng dụng web để quản lý người dùng. Chúng ta có thể tạo ra classes cho các loại người dùng khác nhau, như User, Admin và Guest, sử dụng kế thừa để tạo ra các lớp chuyên biệt.
Giải thích:
- Class
Userchứa các phương thứcloginvàlogout - Class
Adminkế thừa từUservà thêm phương thứcdeleteUser - Class
Guestkế thừa từUservà thêm phương thứcrequestAccess - Các instance của classes
AdminvàGuestsử dụng các phương thức của class của nó và class cơ bản
Mã:
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 Quản lý sản phẩm trong cửa hàng trực tuyến
Trong ví dụ này, chúng ta sẽ tạo các classes để đại diện cho các loại sản phẩm khác nhau trong cửa hàng trực tuyến, như Product, Electronics, và Clothing. Chúng ta cũng sẽ thực hiện đa hình cho phương thức calculateDiscount.
Giải thích:
- Class
Productchứa phương thứccalculateDiscount, tính toán giảm giá 10% mặc định - Class
Electronicsghi đè phương thứccalculateDiscount, cung cấp giảm giá 20% cho điện tử - Class
Clothingghi đè phương thứccalculateDiscount, cung cấp giảm giá 15% cho quần áo - Các instance của classes
ElectronicsvàClothingsử dụng phương thứccalculateDiscountcủa mình để tính toán giảm giá
Mã:
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
calculateDiscount() {
return this.price * 0.1; // 10% giảm giá mặc định
}
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% giảm giá cho điện tử
}
}
class Clothing extends Product {
constructor(name, price, size) {
super(name, price);
this.size = size;
}
calculateDiscount() {
return this.price * 0.15; // 15% giảm giá cho quần áo
}
}
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: Quản lý thư viện
Trong ví dụ này, chúng ta sẽ tạo các classes để quản lý thư viện, bao gồm các classes Book, Magazine và Library. Chúng ta cũng sẽ thực hiện các phương thức để thêm và xóa các mục khỏi thư viện.
Giải thích:
- Các classes
BookvàMagazinekế thừa từ classLibraryItemvà ghi đè phương thứcdisplay - Class
Libraryquản lý bộ sưu tập các mục thư viện, cung cấp các phương thứcaddItem,removeItemvàdisplayItems - Các instance của classes
BookvàMagazineđược thêm và xóa khỏi thư viện, thông tin của chúng được hiển thị sử dụng phương thứcdisplay
Mã:
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