There are other things that you can do with an anonymous function other than assigning it to a variable. You can for example execute it right away:
(function() { ... })();
This is sometimes used to create a scope for the code. Anything declared in the scope is local to it, and you can return a result to the code outside:
var a = (function() {
var answer = 42;
function display() { window.alert(answer); };
return display;
})();
Now the variable a
contains a function that displays the value of the variable answer
, but the variable answer
is local to the scope:
a(); // displays the value
display(); // not available
window.alert(answer); // not available
This pattern is for example used to create plugins for jQuery:
(function($) {
$.fn.blackText = function() {
return this.css('color', '#000');
};
}(jQuery);
The jQuery
object is sent into the scope as the $
parameter, that way the code in the scope can use the $
shortcut even if it has been turned off (using noConflict
) outside the scope.