Possible Duplicate:
why do we need to pass in window and undefined into this jquery plugin?
I've seen jQuery source code does this:
(function(window, undefined){
...
}(window))
I get why is it useful to include undefined, if someone where to change "undefined" before. But window cant be changed. For all I know, it doesnt even need to be used, right? How could this be useful?
They're called anonymous functions because they aren't given a name in the same way as normal functions. Because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later.
The advantage of an anonymous function is that it does not have to be stored in a separate file. This can greatly simplify programs, as often calculations are very simple and the use of anonymous functions reduces the number of code files necessary for a program.
It's an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it's created. It has nothing to do with any event-handler for any events (such as document. onload ). Consider the part within the first pair of parentheses: (function(){})(); ....it is a regular function expression.
An anonymous function is a function with no name which can be used once they're created. The anonymous function can be used in passing as a parameter to another function or in the immediate execution of a function.
Micro optimisation.
Having window
as a local variable is marginally faster than a global variable.
It also minifies better. We can now minify the function parameter to w
and use w.setTimeout
etc instead of window.setTimeout
.
Fewer bytes = better
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With