encapsulation in javascript module pattern

和自甴很熟 提交于 2019-12-17 20:49:17

问题


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(),


来源:https://stackoverflow.com/questions/10362956/encapsulation-in-javascript-module-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!