Why does jQuery wrap itself in a function?

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?

Answers


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

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.


Need Your Help

It's possible to expose new events/properties in a WPF templated control?

wpf events templates properties wpf-controls

Maybe the obvious answer is that I need to use a UserControl but I'd like to know if this is possible.

How to post wordpress functions for my loop in an accordion

php wordpress css3 loops accordion

So I'm trying to create a vertical accordion and with each section of the accordion, I want there to be a blog post. So essentially, i'll have an accordion with 5 of the latest posts. In each post,...