(function () {}) () Declaring / initializing a javascript function

Possible duplicate:
JavaScript: why the shell of anonymous functions?

Hi guys,

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

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

function?

amuses

+7
javascript function initialization
source share
2 answers

A standalone anonymous function is intended to wrap everything in a private namespace, that is, any declared variables do not pollute the global namespace, mainly like a sandbox.

 var test = 1; 

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

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

window.test is undefined because it is in our separate sandbox.

+11
source share

This protects the global namespace from pollution.

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

Now these temporary variables and functions are protected inside this external drop function. The code inside them can use them, but the global namespace is kept clean and free of dirty, unwanted variables.

The global namespace is a valuable resource. We all need to know about its importance for ourselves and, especially, for our children.

+5
source share

All Articles