Possible Duplicate:
How do JavaScript closures work?
I was playing around with the Google Closure Compiler, putting in random code to see what it would do.
It rewrote one of my functions to look something like this:
(function(msg) { console.log(msg); })("Hello World!");
Where it appears that "Hello World"
is the argument passed as msg
to the anonymous function preceding it. I was looking at it for a moment, and had thought that I had seen something similar in jQuery plugins that look something like:
(function( $ ) {
...
})(jQuery);
Which now makes more sense to me, in the scope of conflicts with $
. But what is the primary reason or purpose for passing arguments into an anonymous function like this? Why wouldn't you simply define the arguments as variables within the function? Is there any performance or flexibility advantage to writing functions like this?