A function in JavaScript can be an expression or an expression . When you use a function expression, you can pass it like any other value:
> console.log(function() { 1 + 1; }); > (function() {}) && doExpensiveWork();
One of the things you can do with a function expression immediately calls it. In such cases, the function is called the function expression immediately called (or IIFE for short) :
> (function() { console.log("IIFE running"); })(); IIFE running
This is the same as creating a function and calling it in two stages:
> var notAnIIFE = function() { console.log("running"); }; > notAnIIFE(); running
A functional expression can, of course, take arguments:
> var someFunction = function(x, y) { return x + y; }; > var seven = someFunction(3, 4); > seven 7
So IIFE can also be called with arguments:
> var seven = (function(x, y) { return x + y; })(3, 4); > seven 7
In case of a call like this:
(function($) { })(jQuery);
the value associated with the jQuery name is passed to the function expression as the $ argument. This is similar to doing the following:
var initializePlugin = function($) { }; initializePlugin(jQuery);
but it leaves no trace in the parent namespace (whereas in our second example, our initializePlugin name remains after the completion of our plugin configuration).
Sean Vieira Oct 26 '13 at 18:57 2013-10-26 18:57
source share