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?
As far your questions regarding
window, thewindowin parentheses at the bottom is a reference to the globalwindowobject. The firstwindowis just a name for a parameter. But in this instance it refers to the globalwindowobject since you’re using an anonymous self-invoked function. You could call itmonkeysand it wouldn’t make a difference (of course, you’d have to usemonkeyswithin 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.