...

View Full Version : Resolved Syntax question



ninnypants
03-11-2009, 06:49 PM
What exactly does setting you code up like this do?


(function(){
//more code here
})();


I've seen it used a lot lately and would like to know what the benefits of it are.

mrhoo
03-11-2009, 07:07 PM
It's a one time call to a function that no longer exists after it returns its value.

It lets you return an object or a value, calculated or constructed within the function,
without adding the function itself or any of its internal variables to the environment.

freedom_razor
03-11-2009, 07:10 PM
The code inside this anonymous function will not pollute global namespace.
When you have some code you need to run once and are concerned about possible conflict between your defined names and other that may be in the global namespace, you can put your code inside such anonymous function.

It does more or less the same as:

function myfunction(){
//code here
}
myfunction();
Only in this example you add 1 property to global namespace [myfunction] and the code from your post adds none at all.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum