Possible Duplicate:
What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
I came across a JS file that can be summarized to the code below:
(function(window){
// some codes here
})(window);
I wonder what this block of code means? Has the window special meanings, or it is just a parameter? What are the differences between the two "window" we see in the brackets?
Since this function does not have a name, I assume it is an anonymous function, so is it only invoked once? When is it invoked?
This is called a immediately-invoked anonymous function. (IIAF for short.)
In this case, you are defining a function that takes in a parameter called "window" that overrides the global window
object inside of that scope.
The kicker here is that right after defining the function, you're immediately invoking it, passing in the global window
object, so it is as if you used the global reference within the function closure!
Most of the time, the purpose of this is to avoid polluting the global namespace by way of wrapping all potential variables within an anonymous scope.
As far your questions regarding window
, the window
in parentheses at the bottom is a reference to the global window
object. The first window
is just a name for a parameter. But in this instance it refers to the global window
object since you're using an anonymous self-invoked function. You could call it monkeys
and it wouldn't make a difference (of course, you'd have to use monkeys
within the body of the anonymous function then, to refer to the parameter). So now, you now have a reference to the global window object within your function.
Yes, the function is invoked once and it is invoked as soon as it is defined. This is because it is a self-invoked anonymous function.
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