JavaScriptのオブジェクトを理解する。(買い物カゴを作成する)
-
カートが持つ情報
- カートに入っている商品
- カートの中の合計金額
-
カートが持つ機能
- カートに商品を追加する
- カートから商品を削除する
- 商品の数量を変更する
| /* | |
| 買い物かごをJavaScriptオブジェクトで再現する | |
| */ | |
| var cart = { | |
| // カートに入っている商品 | |
| items: [], | |
| // カートの合計金額 | |
| total: 0, | |
| // 商品追加 | |
| add: function(item, quantity){ | |
| console.log("商品を追加しました"); | |
| this.items.push({ | |
| name: item.name, | |
| price: item.price, | |
| image: item.image, | |
| manufacturer: item.manufacturer, | |
| quantity: quantity | |
| }); | |
| this.calcTotalPrice(); | |
| }, | |
| // 商品削除 | |
| remove: function(index){ | |
| console.log("商品を削除しました"); | |
| this.items.splice(index, 1); | |
| this.calcTotalPrice(); | |
| return this; | |
| }, | |
| // 商品削除 | |
| changeQuantity: function(index, quantity){ | |
| console.log("商品の数量を変更しました"); | |
| var item = this.items[index]; | |
| item.quantity = quantity; | |
| this.calcTotalPrice(); | |
| return this; | |
| }, | |
| // 合計金額計算 | |
| calcTotalPrice: function() { | |
| this.total = 0; | |
| for (var i =0; i< this.items.length; i++) { | |
| this.total += this.items[i].price * this.items[i].quantity; | |
| } | |
| } | |
| }; | |
| // 商品情報 | |
| var items = [ | |
| { | |
| name: "カメラ", | |
| price: 1000, | |
| image: "http://image.jpg", | |
| manufacturer: "Canon" | |
| }, | |
| { | |
| name: "ペン", | |
| price: 8000, | |
| image: "http://image.jpg", | |
| manufacturer: "pilot" | |
| } | |
| ]; |