开发者

Enclosing js function between ()? [duplicate]

This question already has answers here: Closed 11 years ago. 开发者_C百科

Possible Duplicate:

Difference between (function(){})(); and function(){}();

I have seen it a lot by google:

(function(){/*code*/})

Why they enclose their function inside the parethesis? Which is the difference between:

function(){/*code*/}

?

Edit

Ok the questions should have been this:

Why they enclose their code into this:

(function(){/*code*/})();

Instead to write the code directly into the js flow?

Are there any benefits, different behaviour?


I usually use immediate functions to control the variable scope so as not to pollute the global name space. It's a very useful pattern.

(function (window, $, undefined) {
// This pattern gives you the following benefits:
//   * all variables defined in here are private
//   * can safely minify global variables: window, jQuery & undefined
//   * ensures that window, $, undefined mean what you expect
//   * global variables are localized so lookups are faster
}(this, jQuery));

So even if someone does window = ‘Bob’ or the shortcut $ doesn’t equal jQuery but instead is the Prototype library, the code inside this immediate function will still work correctly. While you may think to yourself “I’d never set undefined to something else”, keep in mind you’re not the only one putting code into the page; you can’t afford to have a poorly written ad script from DoubleClick bringing down the site, especially when it is so easily prevented.

JavaScript’s global scope is like a public toilet. You can’t always avoid it, but try to limit your contact with surfaces.


what you see is a self executing function:

var x = (function(bar){
    return bar;
})('foo')

alert(x);


It's usually done to force the parser to treat it as a function expression and not a declaration.


This is because usually the code looks like this:

(function(){/*code*/})();

The reason for the extra parenthesis is that this is not legal syntax:

function(){/*code*/}();


It's needed for immediate functions as @daniellmb said. See explanation of expression closure for more information.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜