Reputation: 183519
I see JQuery plug-ins and other javascript library documents set up like this:
(function($,window,undefined){
...plug-in code...
});
Why is it necessary to wrap the script in a function, and what args does can that function receive?
Upvotes: 1
Views: 156
Reputation: 827326
The args received are:
(function($,window,undefined){
//..
})(jQuery, window);
$
: A reference for the jQuery object, often made for being able to refer to it as the $
alias, since in the outer scope the code might be in "compatibility mode".
window
: The window
argument is often used to shorten identifier lookup. In browser scripting window
is a property of the global object, in order to resolve it, the Identifier Resolution Process has to inspect every scope, until it reaches the global scope. If we add window
as an argument, the lookup will be short, no matter how nested is our function.
In non-browser scripting environments, the window
identifier doesn't even exist, and that pattern is a common way to keep track of the Global object, e.g.:
(function (global, undefined) {
//..
})(this);
Note that the this
value for global code (not function code), always refers to the global object.
undefined
: At last but not least, the undefined
argument, it is used as a "security measure", because undefined
is also a property of the Global object, and in the ECMAScript 3rd Edition Specification, its value is mutable, immagine:
undefined = true;
That would mess up with your code, but if we have an argument, and we don't pass anything to it, it will hold the undefined value.
Fortunately that was fixed on the ECMAScript 5th Edition Specification, undefined
, Infinity
and NaN
are not writable anymore. :)
Upvotes: 5
Reputation: 7872
The reason is in the doc :
to make sure that your plugin doesn't collide with other libraries that might use the dollar sign, it's a best practice to pass jQuery to a self executing function (closure) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution.
Read here : http://docs.jquery.com/Plugins/Authoring
Upvotes: 1
Reputation: 138042
The only scope in Javascript other than global, is function scope. Wrapping a block of code in a function is the only way to ensure that your variables don't leak out into the rest of the code
The only way that function can receive arguments is if it's called as soon as it's defined (in fact, that's the only way this function will ever have its code executed):
(function($,window,undefined){
...plug-in code...
})(jQuery,this,...);
Upvotes: 1