Excellent explanation. Thank you.
On Jun 23, 8:28 am, Scott Sauyet <li...@sauyet.com> wrote: > jerome wrote: > > (function(){ > > ... > > })(); > > > How is this basic to understanding how jQuery works, and how > > JavaScript works? > > The basic idea is that global variables are evil. This technique moves > what would otherwise be global variables into a closure [1], removing > them from the global scope. For example, in the following code > > var count = 0; > function createClickHandler(nbr) { > return function() { > alert("You clicked dead link " + (1 + nbr)); > } > } > var links = document.getElementsByTagName("A"); > for (var i = 0; i < links.length; i++) { > var link = links[i]; > if (link.getAttribute("href") == "#") { > link.onclick = createClickHandler(count++); > } > } > > all the variables used are now available in the global scope, including > "count", "links", the function "createClickHandler", and, perhaps > surprisingly, "i" and "link". You can see for yourself by clicking the > button on this page: > > http://scott.sauyet.com/Javascript/Demo/2009-06-22a/ > > If, however, you surround the code with "(function(){" and "})();", as > you can see at > > http://scott.sauyet.com/Javascript/Demo/2009-06-22b/ > > the variables are no longer defined when you click the button. You've > removed the variables from the global scope. > > As to the syntax, what you are seeing is an anonymous function created > and then immediately applied. You could do this with a named function > like this: > > function myFunc() { > // code here > } > myFunc(); > > but then you've added "myFunc" to the global namespace. By removing the > function name, you are adding nothing at all to the global namespace. > Ideally, this would be accomplished with syntax more like this: > > function() { > // code here > }(); > > i.e., we create the function and apply it. But that syntax is not > legal. For technical reasons, you need to surround the anonymous > function with parentheses to be able to apply it with the "()" operator, > and we end up with > > (function() { > // code here > })(); > > As to how closures manage to keep the global namespace clean, you will > need to read up on closures. [1] > > This has become a very common idiom in JavaScript programming, and it > really is important to understand it if you want to work with any but > the most basic of modern scripts. > > Cheers, > > -- Scott > > [1]http://www.google.com/search?q=javascript+closure