Define and execute an anonymous JavaScript function in a single step

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. Smiling

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 ... Eye-wink
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". Laughing out loud
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

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Lambda calculus. I'm not

Lambda calculus. I'm not sure how useful this link is in this situation Laughing out loud

Re: Lambda calculus

It's useful to know how other languages support functions as arguments to other functions. And it turned out that the article has to be updated to include some reference to JavaScript too. Smiling

Syndicate content