Closing js function between ()?

Possible duplicate:
Difference between (function () {}) (); and function () {} ();

I have seen a lot on Google:

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

Why do they enclose their function within the pasezes? What's the difference between:

function(){/*code*/}

?

Edit

Well, the questions should have been like this:

Why do they enclose their code:

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

Instead of writing code directly to js stream?
Are there any advantages, different behaviors?

+5
source share
5 answers

what you see is a self-executing function:

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

alert(x);
+5
source

I usually use immediate functions to control the scope of variables so as not to pollute the global namespace. This is a very useful model.

(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));

- window = ‘Bob’ $ jQuery, Prototype, . : "Id undefined - ", , , ; script DoubleClick, , .

JavaScripts . , .

+9

, , .

+4

, :

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

, :

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

This is necessary for immediate functions, as @daniellmb said. See the explanation for closing an expression for more information .

0
source

All Articles