Encapsulation In Javascript Module Pattern
I was reading this link http://addyosmani.com/largescalejavascript/#modpattern And saw the following example. var basketModule = (function() { var basket = []; //private return {
Solution 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() {
functionBasket(){
var basket = []; //privatethis.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(){returnnewBasket;}
}
}());
//usagevar basket1 = basketModule.basket(),
basket2 = basketModule.basket(),
Post a Comment for "Encapsulation In Javascript Module Pattern"