当我们开发一个程序,或者一个页面的时候,我们常常因为不知道如何下手,方法都有哪些,页面的内容怎么排,不同内容之间有什么关系等等。当使用「面向过程」思维去思考的时候,就分不清步骤了。这时候,「面向对象」的思维能给我们很好的提示。
如有一个购物页面,有商品信息(价格、名称、数量、图片等),点击商品可以加入购物车。还有一个购物车信息(总价、数量)等。
我们可以把「商品」和「购物车」分别作为两个类,然后建立一个购物车类,让它拥有购物车信息的属性和方法,让「商品」拥有商品信息的属性和方法,这样就能很好的实现「面向对象」的思维。
-
商品类:拥有商品信息的属性和方法,如名称、价格、数量、图片等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
class Goods { constructor(name, price, quantity = 0, img) { this.name = name; this.price = price; this.quantity = quantity; this.img = img; } getTotalPrice() { return this.price * this.quantity; } isChoosed() { return this.quantity > 0; } decreaseQuantity() { if (this.quantity <= 0) return 0; this.quantity--; } increaseQuantity() { this.quantity++; } }
-
购物车类:拥有购物车信息的属性和方法,如总价、数量等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
class ShoppingCart { constructor() { this.totalPrice = 0; this.quantity = 0; this.goods = []; } addGoods(goods) { this.goods.push(goods); this.totalPrice += goods.getTotalPrice(); this.quantity += goods.quantity; } removeGoods(goods) { const index = this.goods.indexOf(goods); if (index === -1) return; this.goods.splice(index, 1); this.totalPrice -= goods.getTotalPrice(); this.quantity -= goods.quantity; } clear() { this.goods = []; this.totalPrice = 0; this.quantity = 0; } }
到此,很形象的就把整个功能写完了。当点击商品的时候,我们可以创建一个商品对象,然后把它添加到购物车中,当点击购物车中的商品的时候,我们可以从购物车中删除商品。
1
2
3
4
5
6
7
8
9
10
useEffect(() => {
const goods1 = new Goods("apple", 10, 100);
const goods2 = new Goods("banana", 20, 200);
const cart = new ShoppingCart();
cart.addGoods(goods1);
cart.addGoods(goods2);
const totalPrice = cart.totalPrice;
console.log("totalPrice:", totalPrice); // 5000
}, []);