0

I have seen many js frameworks (including jquery) using closure around their main function scope. For example,

var obj = (function(){
    return {
        test : function(){
            alert('test');
        }
    }
})();
obj.test()

jquery source, http://code.jquery.com/jquery-1.7.2.js

Whats the need that extra 'closure' around the 'function'? Or whats the difference if we are using it like,

var obj = function(){
    return {
        test : function(){
            alert('test');
        }
    }
}();
obj.test()

Both have the same behavior and function definition itself puts all the local variable inside a new scope... so why the extra closure?

Jim Jose
  • 1,279
  • 10
  • 17

2 Answers2

4

It adds the "big"object\library functions, and not adding them to the global object.

The two options you pasted are just like the difference between:

var foo = (2);
var foo = 2;

No difference...


Update:

Now I undersatnd your question, parentheses don't create new scope in javascript, only functions.

gdoron is supporting Monica
  • 142,542
  • 55
  • 282
  • 355
  • @gdoron I thought he is asking why not just `var obj = { test : function(){ alert('test'); } };` – xdazz May 10 '12 at 09:06
0

That is just a convention to be able to easily distinguish self-executing functions from normal functions.

stewe
  • 40,424
  • 13
  • 77
  • 74