關於單例及模塊模式,之前寫過一篇博客 。
模塊模式返回一個對象,這個對象有一些私有屬性和方法,並且提供了api來訪問這些私有數據。
let singleton = function(){
//私有變量和函數
let privateVariable = 10;
function privateFunction(){
return false;
}
//特權方法和屬性
return {
publicProperty : true,
publicMethod: function(){
privateVariable++;
return privateFunction();
}
}
}();
下面使用模塊模式來實現一個簡單的購物車。
購物車就是一個模塊,商品信息是購物車的私有數據,外部無法訪問,我們需要提供一些方法來操作商品信息。
let shoppingCart = function () {
let goodsList = [];
return {
addItem: (item) => {
goodsList.push(item);
},
removeItem: (index) => {
goodsList.splice(index, 1);
},
getCount: () => {
return goodsList.length;
},
getTotalPrice: () => {
let price = 0;
goodsList.forEach(item => {
price += item.price;
})
return price;
}
}
}();
shoppingCart.addItem({
name: 't-shirt',
price: 199
});
shoppingCart.addItem({
name: 'umbrella',
price: 45
});
shoppingCart.addItem({
name: 'shoes',
price: 365.9
});
console.log(shoppingCart.getCount());
console.log(shoppingCart.getTotalPrice());
shoppingCart.removeItem(1);
console.log(shoppingCart.getCount());
console.log(shoppingCart.getTotalPrice());