views:

91

answers:

3

Possible Duplicate:
JavaScript: Why the anonymous function wrapper?

Hi Guys,

I would like to ask you what is the reason of wrapping everything in

(function() {
  document.write("Hello World!");
})(); 

function ?

cheers

A: 

Its an anonymous function.

Kangkan
ok but why we need to use them? what's the usage examples are? cheers
Marcin
+5  A: 

That "protects" the global namespace from contamination.

(function() {
  var something = "a thing";
  // ...
  if (something != "a thing") alert("help!");
  // ...
  function utility(a, b) {
    // ...
  };
  // ...
})();

Now, those temporary variables and functions are all protected inside that outer throw-away function. Code inside there can use them, but the global namespace is kept clean and free of dirty, unwanted variables.

The global namespace is a precious resource. We should all be aware of its importance to ourselves and, especially, for our children.

Pointy
+6  A: 

Self executing anonymous function's main purpose is to wrap everything in a private namespace, meaning any variables declared do not pollute the global namespace, basically like a sandbox.

var test = 1;

test would pollute the global namespace, window.test would be set.

(function() {
    var test = 1; alert( test );
})();

window.test is undefined, because it's in our private sandbox.

meder