1. 创建一个简单的购物车
面向对象编程(OOP)的核心思想之一是封装。在这个案例中,我们将创建一个简单的购物车,它将允许用户添加商品,并计算总价。
class ShoppingCart {
constructor() {
this.items = [];
}
addItem(item) {
this.items.push(item);
}
getTotal() {
return this.items.reduce((total, item) => total + item.price, 0);
}
}
class Item {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
// 使用
const cart = new ShoppingCart();
cart.addItem(new Item('Apple', 0.5));
cart.addItem(new Item('Banana', 0.3));
console.log(cart.getTotal()); // 输出 0.8
2. 实现一个用户管理系统
在这个案例中,我们将创建一个用户管理系统,它将允许我们添加、删除和查找用户。
class UserManager {
constructor() {
this.users = [];
}
addUser(user) {
this.users.push(user);
}
deleteUser(username) {
this.users = this.users.filter(user => user.username !== username);
}
findUser(username) {
return this.users.find(user => user.username === username);
}
}
class User {
constructor(username, email) {
this.username = username;
this.email = email;
}
}
// 使用
const userManager = new UserManager();
userManager.addUser(new User('Alice', 'alice@example.com'));
userManager.addUser(new User('Bob', 'bob@example.com'));
console.log(userManager.findUser('Alice').email); // 输出 alice@example.com
3. 创建一个待办事项列表
在这个案例中,我们将创建一个待办事项列表,用户可以添加、删除和标记待办事项为完成。
class TodoList {
constructor() {
this.todos = [];
}
addTodo(todo) {
this.todos.push(todo);
}
deleteTodo(index) {
this.todos.splice(index, 1);
}
markAsCompleted(index) {
this.todos[index].completed = true;
}
}
class Todo {
constructor(description) {
this.description = description;
this.completed = false;
}
}
// 使用
const todoList = new TodoList();
todoList.addTodo(new Todo('Buy milk'));
todoList.addTodo(new Todo('Read a book'));
todoList.markAsCompleted(0);
console.log(todoList.todos[0].completed); // 输出 true
4. 实现一个简单的银行账户系统
在这个案例中,我们将创建一个银行账户系统,用户可以存款、取款和查看余额。
class BankAccount {
constructor(accountNumber, balance = 0) {
this.accountNumber = accountNumber;
this.balance = balance;
}
deposit(amount) {
this.balance += amount;
}
withdraw(amount) {
if (amount <= this.balance) {
this.balance -= amount;
} else {
console.log('Insufficient funds');
}
}
getBalance() {
return this.balance;
}
}
// 使用
const account = new BankAccount('123456789');
account.deposit(100);
account.withdraw(50);
console.log(account.getBalance()); // 输出 50
5. 创建一个图书管理系统
在这个案例中,我们将创建一个图书管理系统,它将允许我们添加、删除和查找图书。
class Library {
constructor() {
this.books = [];
}
addBook(book) {
this.books.push(book);
}
deleteBook(isbn) {
this.books = this.books.filter(book => book.isbn !== isbn);
}
findBook(isbn) {
return this.books.find(book => book.isbn === isbn);
}
}
class Book {
constructor(title, author, isbn) {
this.title = title;
this.author = author;
this.isbn = isbn;
}
}
// 使用
const library = new Library();
library.addBook(new Book('JavaScript: The Good Parts', 'Douglas Crockford', '978-0596009205'));
console.log(library.findBook('978-0596009205').title); // 输出 JavaScript: The Good Parts
6. 实现一个天气应用
在这个案例中,我们将创建一个简单的天气应用,它将允许用户查询某个城市的天气。
class WeatherApp {
constructor(apiKey) {
this.apiKey = apiKey;
}
getWeather(city) {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${this.apiKey}`;
fetch(url)
.then(response => response.json())
.then(data => {
console.log(`The weather in ${city} is ${data.weather[0].description}`);
});
}
}
// 使用
const weatherApp = new WeatherApp('your_api_key_here');
weatherApp.getWeather('London');
7. 创建一个简单的游戏
在这个案例中,我们将创建一个简单的猜数字游戏,用户需要猜测一个随机生成的数字。
class GuessingGame {
constructor() {
this.secretNumber = Math.floor(Math.random() * 100) + 1;
}
guess(number) {
if (number === this.secretNumber) {
console.log('Congratulations! You guessed the right number!');
} else if (number < this.secretNumber) {
console.log('Too low!');
} else {
console.log('Too high!');
}
}
}
// 使用
const game = new GuessingGame();
game.guess(50); // 输出 Too high!
game.guess(75); // 输出 Too low!
game.guess(76); // 输出 Congratulations! You guessed the right number!
8. 实现一个简单的博客系统
在这个案例中,我们将创建一个简单的博客系统,用户可以添加、删除和查看文章。
class Blog {
constructor() {
this.articles = [];
}
addArticle(article) {
this.articles.push(article);
}
deleteArticle(index) {
this.articles.splice(index, 1);
}
getArticles() {
return this.articles;
}
}
class Article {
constructor(title, content) {
this.title = title;
this.content = content;
}
}
// 使用
const blog = new Blog();
blog.addArticle(new Article('Hello World', 'This is my first blog post.'));
console.log(blog.getArticles()[0].title); // 输出 Hello World
9. 创建一个简单的日历应用
在这个案例中,我们将创建一个简单的日历应用,用户可以查看当前日期和选择日期。
class Calendar {
constructor() {
this.currentDate = new Date();
}
getCurrentDate() {
return this.currentDate.toDateString();
}
selectDate(date) {
this.currentDate = date;
}
}
// 使用
const calendar = new Calendar();
console.log(calendar.getCurrentDate()); // 输出 当前日期的字符串表示
calendar.selectDate(new Date('2023-12-25'));
console.log(calendar.getCurrentDate()); // 输出 2023-12-25 的字符串表示
10. 实现一个简单的待办事项提醒应用
在这个案例中,我们将创建一个简单的待办事项提醒应用,用户可以添加待办事项并设置提醒时间。
class ReminderApp {
constructor() {
this.reminders = [];
}
addReminder(title, date) {
this.reminders.push({ title, date });
}
checkReminders() {
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
this.reminders.forEach(reminder => {
if (reminder.date.toDateString() === today.toDateString()) {
console.log(`Reminder: ${reminder.title}`);
}
});
}
}
// 使用
const reminderApp = new ReminderApp();
reminderApp.addReminder('Buy groceries', new Date('2023-12-25'));
reminderApp.checkReminders(); // 输出 Reminder: Buy groceries
通过这些实战案例,你可以更好地理解JavaScript面向对象编程的精髓,并在实际项目中应用这些知识。希望这些案例能够帮助你成为一个更优秀的开发者!
