-1

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?

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

I would only add that this is all part of a technique called unobtrusive JavaScript: en.wikipedia.org/wiki/Unobtrusive_JavaScript
0

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

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.