Its called an anonymous closure and prevents jquery from leaking variables into the global scope. The anonymous closure is a function that is defined without a name.
//named functions a very common //they are just functions assigned to a variable var myfunction = function(){}; //the anonymous function is not assigned to a variable //it's legal and the following lines show several legal but //relatively useless lines of script that execute just fine but //have no effect, they are all anonymous statements (function(){ var foo; }); (6+1); ('hello '+'world'); //The anonymous function is a little special because //it can be executed immediately by adding (); //with firebug enabled the following line would print\ //'hello world' to the console (function(){ var foo; console.log('hello world'); })(); So why go through all that trouble? The answer is to keep the global scope clean and uncluttered. variable defined in the anonymous closure are available inside that scope but not outside it, so variable collision/confusion between libraries and your code can be avoided and memory leaks more easily avoided as well. //global or outer scope (function(){ //anonymous or inner scope. var foo = 'hello world'; })(); //true if(foo === undefined){ console.log('now I understand anonymous closures!'); } Hope that helps! Thatcher On Tue, Jun 9, 2009 at 8:39 AM, darwin liem <darwin.l...@yahoo.com> wrote: > its javascript, it got nothing to do with jQuery. > for example > > function funcname1(){ /* do something here */ } > > now we do something else like setTimeout to trigger the funcname1 > setTimeout("funcname1",1000); <-- this will delay until 1 second to trigger > the function > > another way to call it > setTimeout(function(){ funcname1(); },1000); <-- this will do the same. > > basically function is to do a code that was need to be executed as string > yet written as normal code... at least that what i learned so far. and it > got nothing to do with jQuery it's part of javascript. jQuery use the same > coding rules / grammar so that programmer do not need to familiarize with > new function as parameter calling. yup, botrh sample i show explain that it > use the function as parameter of another function (in this case setTimeout() > function). > > hope it helps > > Best Regards > Darwin Liem > > --- On *Tue, 6/9/09, wangsuya <wang.s...@gmail.com>* wrote: > > > From: wangsuya <wang.s...@gmail.com> > Subject: [jQuery] jQuery's code first line (function(){・・・・・ > To: "jQuery (English)" <jquery-en@googlegroups.com> > Date: Tuesday, June 9, 2009, 3:19 AM > > > Hi everyone > > Know I try to study javascript using jQuery code,but first I do not > know why jQuery start with (function(){.... > What is "(" function? Why using (function(){ > start jQuery? Thanks in advance. > > Wang Suya > > > -- Christopher Thatcher