Possible Duplicate:
What does (function($) {})(jQuery); mean?
I’ve seen a lot of jQuery code with the following sort of syntax, but I don’t really understand what it means. It shows up in this answer and this answer on a question about code organization. Both talk about namespacing, so I’m guessing that’s what it accomplishes.
var foo = (function () {
var someVar;
function someFunc() {
return true;
}
})();
Is this for namespacing, and how does it work? Sometimes there is a name (the namespace?) in the final set of parentheses, sometimes not. What is the difference between the two?
The
()that wrap the function turns the anonymous function declaration into a function expression that can then be immediately invoked with the()that follows the expression.In this case, the outer
()really isn’t necessary since thevar foo =would turn it into an expression. Also, the value offoowill beundefinedsince the function invocation doesn’t return anything.It can be used for creating a new variable scope, since a function is the only way to accomplish that in javascript. (Javascript doesn’t have block scope.)
So the
someVarvariable is not accessible to the outer scope. There may be times when it is desirable to make it accessible in a controlled manner. To do this, you can pass a function out of that scope which referencessomeVar. Then after the function invocation exits, its execution context will remain intact, andsomeVarwill be available in whatever manner the function you passed out provides.This is called creating a
closure.Let’s say you passed a value into the invocation, and assigned it to
someVar. You could thenreturna function out of the invocation to thefoovariable. If that function you return referencessomeVar, then you could use that function to get its value.As you can see, the function now referenced by
foocan still accesssomeVar.Let’s say you changed it so that the function returned to
foocan accept an argument, which will update the value ofmyVar.Now you can see, that the function in
fooreally does access that variable, as it is able to change its value, and reference the new value that it previously set.