encapsulation in javascript module pattern

◇◆丶佛笑我妖孽 提交于 2019-11-28 13:46:39

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