Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enclosing js function between ()? [duplicate]

Tags:

javascript

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?

like image 457
dynamic Avatar asked Apr 01 '11 20:04

dynamic


3 Answers

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.

like image 147
SavoryBytes Avatar answered Nov 08 '22 23:11

SavoryBytes


what you see is a self executing function:

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

alert(x);
like image 26
ezmilhouse Avatar answered Nov 08 '22 23:11

ezmilhouse


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

like image 4
Pointy Avatar answered Nov 09 '22 00:11

Pointy