views:

877

answers:

2

I was reading the jQuery source and I was wondering why the entire source file was wrapped in an anonomous function.

(function(){
  ...
})();

Is this something which helps not to pollute the global namespace? Why is it there and how does it work?

+17  A: 

It uses the function body to provide its own scope rather than introducing a large number of globals that could be accidentally changed by external code.

Eg.

(function (){
    var someConstantValue = ...;
    myCoolFunction = function(){ return someConstantValue * 5; }
})();

myCoolFunction();

If the function scope were not introduced it would be possible to accidentally change someConstantValue by introducing other code (or another library)

someConstantValue = someOtherValue; // this won't change the behaviour of myCoolFunction
olliej
+5  A: 

You're right that it will prevent pollution of the global namespace.

All of the variables and functions that jQuery needs are created inside of that function, which keeps those functions and variables from bleeding out into the global namespace. If you look at this block of code:

var jQuery = window.jQuery = window.$ = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
};

it's actually connecting the jQuery initializer to the outside world by setting window.jQuery and window.$ to the initialization function. That's the only place where the variables inside the wrapper function are directly available outside of the wrapper.

Notice too that the whole function is wrapped like this (function,,,)() which will execute that function as soon as the file loads.

Matt Ephraim