版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/latency_cheng/article/details/89284590
关于单例及模块模式,之前写过一篇博客 。
模块模式返回一个对象,这个对象有一些私有属性和方法,并且提供了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());