Forum Moderators: open

Message Too Old, No Replies

Please explain (function() { . . . })();

Stoneage JS programmer not understand

         

idfer

12:08 am on Sep 1, 2009 (gmt 0)

10+ Year Member



Hi folks, i'm trying to use the YUI Javascript library and looking at one of their examples, the code looks something like this:

[pre](function() {

var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
var DDM = YAHOO.util.DragDropMgr;

...

})();[/pre]

Now i'm familiar with older Javascript and programming in general, but i don't quite understand what's the benefit of wrapping all the code inside a (function)(). Can someone please exlain.

Also, is there an online reference manual for Javascript that explains this type of functionality, namespaces etc? Something in a format similar to php.net's manual would be fantastic. Thanks!

Alternative Future

12:27 pm on Sep 1, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi idfer

I once asked the same question, and received a full explanation here [webmasterworld.com...]

HTH

-Gs

idfer

4:15 pm on Sep 1, 2009 (gmt 0)

10+ Year Member



Nice, thanks for the link it explains it quite well. So is it a good/bad idea to put as much of my Javascript code inside these self-calling anonymous functions?

Still looking for a good online reference manual. :)

whoisgregg

7:32 pm on Sep 2, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If you're writing a public javascript library that you expect people to use alongside other public javascript libraries, it may make sense to use these.

Otherwise, you'll be fine to just ignore it. :)