What is the purpose of writing a function inside parentheses?
thanks.PHP Code:(function()
{
var myvar = xxx;
// my function code here....
}
)()
| SitePoint Sponsor |


What is the purpose of writing a function inside parentheses?
thanks.PHP Code:(function()
{
var myvar = xxx;
// my function code here....
}
)()


It is executed immediately.
Birnam wood is come to Dunsinane
+++
Divide By Cucumber Error. Please Reinstall Universe And Reboot
+++
Cross-Browser.com, Home of the X Library


AutisticCuckoo, are you meaning on page load? I mean, is this any different from simply having the code outside function()?





It will not wait for page load, it will execute immediatetly when found. Variables defined within this self-executing anonymous function will also not be global. Meaning no pollution.


@cbiti: yes, the code will execute as soon as the script is read and parsed. That will probably be before the entire page has been loaded, unless the script is at the very end.
The only difference I can think of from having the code outside function() is that you will not pollute the global namespace with any variable declarations you make inside the function.
@MikeFoster:![]()
![]()
(Does your computer have an 'Anthill Inside' sticker on it?)
Birnam wood is come to Dunsinane


Thanks very much to all of you guys.
LOL!Originally Posted by AutisticCuckoo
I have to admit that I only recently learned of Mr. Pratchett - in fact, because of your sig!
It gets worse. I have, before now, waited for a pen to perform a macro.
-- (Terry Pratchett, alt.fan.pratchett)
Cross-Browser.com, Home of the X Library




I rarely write anonymous function that execute immediately in this way. I just wonder how different is it with using Function
Bookmarks