encapsulation in javascript module pattern

前端 未结 1 1465
孤城傲影
孤城傲影 2020-12-11 05:54

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

And saw the following example.

var basketModule = (function() {
var b         


        
相关标签:
1条回答
  • 2020-12-11 06:28

    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(),
    
    0 讨论(0)
提交回复
热议问题