It's very important becuase the symbol $ is used by other javascript
libraries and it can cause a conflict if you use it outside of the anonymous
function.

For example another sloppy library might have a global definition

var $ = function(){
   alert('Not Cool Man!');
};

then if you tried to use jQuery

$("#mycoolapp").coolPlugin().beCool();

and yould get the alert, 'Not Cool Man!'

But jQuery doesnt stand for such sloppy nonsense so we do:

jQuery.noConflict();

and write our plugin still using $ like so:

(function($){
   $.fn.coolPlugin = function(){
     //do cool stuff and feel free to use $ and know
     // it means jQuery and not the lame alert function
     //declared globally by sloppy library X
   }
})(jQuery);

On Wed, Oct 15, 2008 at 9:09 AM, Mike Alsup <[EMAIL PROTECTED]> wrote:

>
> > Plugins are supposed to use this:
> >
> > (function($) {
> >     // Plugin code
> >
> > }) (jQuery)
> >
> > I know what it does (allows the use of $ within the script), but how
> > does it actually work? Is it somehow casting the function object as
> > the jQuery object? It always seemed odd to me, and I haven't seen this
> > idiom elsewhere.
>
> Consider this bit of code:
>
> // declare a function that accepts an argument
> var myFn = function(myParam) {
>    // inside here I can use myParam freely
> };
> // call the function and pass an argument
> myFn(3);
>
>
> Now, change what you call the parameter name and what you pass to the
> function
>
> var myFn = function($) {
>    // inside here I can use $ freely
> };
> // call the function and pass jQuery as the argument
> myFn(jQuery);
>
>
> Now do it all in one step, as an anonymous function:
>
> (function($) {
>    // inside here I can use myParam freely
> })(jQuery);
>
>
>
>
>


-- 
Christopher Thatcher

Reply via email to