encapsulation in javascript module pattern

2019-01-20 11:00发布

问题:

I was reading this link http://addyosmani.com/largescalejavascript/#modpattern

And saw the following example.

var basketModule = (function() {
var basket = []; //private

return { //exposed to public
       addItem: function(values) {
            basket.push(values);
        },
        getItemCount: function() {
            return basket.length;
        },
        getTotal: function(){
            var q = this.getItemCount(),p=0;
            while(q--){
                p+= basket[q].price;
            }
        return p;
        }
      }
}());

basketModule.addItem({item:'bread',price:0.5});
basketModule.addItem({item:'butter',price:0.3});

console.log(basketModule.getItemCount());
console.log(basketModule.getTotal());

It stats that "The module pattern is a popular design that pattern that encapsulates 'privacy', state and organization using closures" How is this different from writing it like the below? Can't privacy be simply enforced with function scope?

var basketModule = function() {
var basket = []; //private
       this.addItem = function(values) {
            basket.push(values);
        }
        this.getItemCount = function() {
            return basket.length;
        }
        this.getTotal = function(){
            var q = this.getItemCount(),p=0;
            while(q--){
                p+= basket[q].price;
            }
        return p;
        }

}

var basket = new basketModule();

basket.addItem({item:'bread',price:0.5});
basket.addItem({item:'butter',price:0.3});

回答1:

In the first variant you create an object without the possibility to create new instances of it (it is an immediately instantiated function). The second example is a full contructor function, allowing for several instances. The encapsulation is the same in both examples, the basket Array is 'private' in both.

Just for fun: best of both worlds could be:

var basketModule = (function() {
   function Basket(){
        var basket = []; //private
        this.addItem = function(values) {
            basket.push(values);
        }
        this.getItemCount = function() {
            return basket.length;
        }
        this.getTotal = function(){
            var q = this.getItemCount(),p=0;
            while(q--){
                p+= basket[q].price;
            }
        return p;
       }
     }
   return {
     basket: function(){return new Basket;}
   }
}());
//usage
var basket1 = basketModule.basket(), 
    basket2 = basketModule.basket(),