0

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?

Community
  • 1
  • 1
corazza
  • 31,222
  • 37
  • 115
  • 186

4 Answers4

2

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.

keune
  • 5,779
  • 4
  • 34
  • 50
2

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.

Aliostad
  • 80,612
  • 21
  • 160
  • 208
  • I would only add that this is all part of a technique called unobtrusive JavaScript: http://en.wikipedia.org/wiki/Unobtrusive_JavaScript – Pavel Veller Apr 28 '12 at 11:31
0

Note parentheses in the last line: (). The function is defined and immediately called: (function() { })();

return { ... } returns an object having a method addItem

tech-man
  • 3,166
  • 2
  • 17
  • 18
0

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

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Rune FS
  • 21,497
  • 7
  • 62
  • 96