开发者

What happens when you put a function in parentheses? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

What do parentheses s开发者_如何转开发urrounding 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?:

(function() {
   // ...
})();

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:

 var counter = 0;
 window['inc'] = function() {
    return counter++;
 };

vs.

 (function() {
    var counter = 0;
    window['inc'] = function() {
       return counter++;
    };
 })();

Both of these have the effect of defining a function window.inc that returns a counter that gets incremented; however, in the first version, counter is actually visible to all other modules, because it is in the global scope, whereas the latter ensures that only window.inc can access counter.

Note that the code creates a function and immediately invokes it (that's what the last parens are for).


The unofficial name is an 'immediate function' - the basic idea is that the function is defined and called on the fly.

Here's a simple example:

http://javascriptmountain.com/2011/06/functions/immediate-functions-in-javascript-the-basics/

The parentheses are actually not necessary unless the return value of the function is assigned to a variable, but they are usually used for readability.

The reason it is done in situations like jquery plugins is that it provides a sort of 'sandbox' for executing code. Say we did the following:

(function($) {
   // augment $ with methods
}(jQuery));

this defines a function that takes in one parameter, then IMMEDIATELY calls the function, passing in the global jquery object. Any vars that are declared and used inside the immediate function will be locally scoped to the function, and will not interfere with global scope or disrupt any global variables that may have been declared in other pieces of javascript code being used (important for libraries intended to be used with large amounts of other code).

However, since we are passing in the global jquery object when we call the function, we can still add methods and properties to the '$' parameter inside of the function that will hang around on the jquery object after the function completes.

Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜