Reputation: 32374
I was reading another question, and I saw this:
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;
}
}
}());
Can you please explain why does he wrap the function in ( and )
's? Also, what is the purpose of that return
? Couldn't he just write self.addItem = ...
and so on?
Upvotes: -1
Views: 134
Reputation: 21752
The intention of the code is to create an object with three methods. addItem,getItemCount and getTotal. They all depend on state represented by basket.
if basket was defined globally that state would be exposed (and there could only ever be one variable basket. both of those can lead to issues so by wrapping the entire declaration the state is encapsulated and only accessible from the created object.
There are other ways of achieving the same and the pro's and con's are related to style and how many objects of that particular type you're going to need.
wrapping the function(){}()
is required since function(){}()
will not parse
Upvotes: 0
Reputation: 81700
That is called javascript Module Pattern. Defining a function and calling it immediately to prevent variables to be in the global space or to define a function name.
Upvotes: 1
Reputation: 5795
When you wrap a function with parantheses, and add ()
to the end of it, it's a self executing function.
(function() x() {
//do something;
})();
And, by returning he's making basket
variable somewhat private. Try getting basketModule.basket
from anywhere else, and you'll get undefined.
Upvotes: 2
Reputation: 3256
Note parentheses in the last line: ()
. The function is defined and immediately called:
(function() { })();
return { ... }
returns an object having a method addItem
Upvotes: 0