Possible Duplicate:
What do parentheses surrounding a JavaScript object/function/class declaration mean?
I see functions inside parentheses in jQuery plugins and the like.
For example,
(function(args) {
// ...
})(localVariable);
What does this do, exactly?
You mean something like the following?:
This basically ensures that any “var” declarations are kept private (they are scoped to the anonymous function in which they have been placed) rather than global. For example, consider:
vs.
Both of these have the effect of defining a function
window.incthat returns a counter that gets incremented; however, in the first version,counteris actually visible to all other modules, because it is in the global scope, whereas the latter ensures that onlywindow.inccan accesscounter.Note that the code creates a function and immediately invokes it (that’s what the last parens are for).