I've seen the following code in jQuery's source and various jQuery plugins, but I did not really understand what it is meant to do:
(function() {
.... // some code
})();
Now reading the page about
writing jQuery plugins, it simply all makes sense.
They explain it pretty well:
(function() {
// put plugin code here
var xyz; // xyz is NOT a global variable, it is only visible inside this function
})(); // execute the function immediately!
The additional parentheses are necessary! You can't execute an anonymous function without them.
And to take this further ...
function($) {
// plugin code here, use $ as much as you like
})(jQuery);
We pass "jQuery" to the function and can now use whatever alias for jQuery we like. So instead of "$" you could also use any other valid JavaScript variable name.
Let's say ... what if we wanted to refer the global "window" object as "glass".
function(glass) {
// here "glass" refers to the "window" variable that is defined outside this function
// and of course we could define our own "window" variable ...
})(window);
Comments
Lambda calculus. I'm not
Re: Lambda calculus