Imagine this:
var sayHello = function(name) { alert('Hello, ' + name); } sayHello('World'); If we don't need to call sayHello more than once, we could make the function anonymous (not give it a name) and call it directly by replacing "sayHello" in the second line with the "function..." part from the first line: function(name) { alert('Hello, ' + name); }('World'); For syntactical purposes, we must wrap the function definition in parens, like so: (function(name) { alert('Hello, ' + name); })('World'); So we define an anonymous function and then immediately call it. Functionally, this is identical to just doing: alert('Hello, World'); So what's the point? The point is a user might be using jQuery with another library that also has a function called $ (remember, $ is a valid function/variable name in javascript, there's nothing magical about it). jQuery's $ function is just a shortcut to a function called "jQuery" so $('div') is actually the same as jQuery('div'). If you were using (for example) Prototype on the same page as jQuery, you might let Prototype take over $ and access jQuery via the "jQuery" function. This makes a problem for plugin developers. Since the $ function might not be jQuery's $ function, it isn't safe for jQuery plugins to use it. So jQuery plugin developers have to use the "jQuery" function, which isn't as convenient as using $. That's where the anonymous function trick comes in. By doing: (function($) { /* stuff here */ })(jQuery); Now everything in the scope of the function will use the function parameter version of $, not the global version. And since we pass in a reference to the "jQuery" function, everything in the scope of the anonymous function will be able to reference the jQuery function as $ without changing or overwriting the global $ function. Functionally, it's similar to: var old$ = $; $ = jQuery; /* stuff here */ $ = old$; Except that would actually change the global $ function temporarily, which could have undesirable consequences in a multithreaded environment. Also, the anonymous function method has the added benefit of giving all of your plugin specific variables some local scope instead of making them all global. Google search 'javascript closures' or 'javascript anonymous functions' for more info. Hope that helps. --Erik On 5/17/07, Shuai Yang <[EMAIL PROTECTED]> wrote:
I found Jörn Zaefferer's "jQuery plugin authoring guide" at http://bassistance.de/2006/12/27/jquery-plugin-authoring-guide/, there i found javascript syntax like this: ======================== (function() { // some code here })(); ======================== (function($) { // some code here })(jQuery); ======================== it really works,but i donno what exactly this syntax means,anyone can explain it? great thanks!