Tuesday, December 23, 2008

What a heck is a (function ($){ ... })(jQuery)

Recently I wrote two articles on how to extend jQuery using its plug in system and a shorthand for that. If you look into them closely they are actually the same thing. The only difference being that the code in first one is wrapped in this anonymous JavaScript function:

(function ($) { 
    // code goes here 
})(jQuery)

Little research shows that this allows the use of $ within this function without conflicting with other JavaScript libraries who are using it. Basically, since we are setting $ as  a parameter, $ will overwrite any globally defined variables/references of $ in that particular anonymous function.

// Assume "$" is a prototype reference 
(function ($) { 
    // Here "$" is a jQuery reference 
})(jQuery)

So basically it’s an anonymous function that lets jQuery play nicely with other javascript libraries that might have $ variable/function. Also if you notice, all jQuery plugins code is wrapped in this anonymous function.

NOTE:
The following two javascript codes are equivalent:

// Code 1:
(function ($) { 
    // Javascript code 
})(jQuery)

// Code 2:
var myFunction = function ($) { 
    // Javascript code 
};
myFuntion(jQuery);

12 comments:

  1. thanks for clarifying that ! Always nice to really understand what your doing instead of just copy/pasting the codes :)

    ReplyDelete
  2. Thanks for post! It's a very useful information for me. I think this way better than use var $j = jQuery.noConflict(); for preventing a conflicts with other javascript libraries.

    ReplyDelete
  3. How do you use this? Sorry i'm very new to both Javascript and JQuery.
    I'd like to be able to achive the effect of

    $output.='jQuery("#subscribe_user_'.$user.'").show()';

    jQuery(function($){
    var id = $.target.attr("id");
    alert(id);
    }

    but this obviously doesn't work

    ReplyDelete
  4. Hi, unfortunaltely, I don't understand the difference :(
    I don't understand the meaning of the (jQuery) between parentheses at the end of the function.
    Thanks

    ReplyDelete
  5. Great! Thank you very much.

    ReplyDelete
  6. thanks for the clarification.

    ReplyDelete
  7. Thanks for this post

    ReplyDelete
  8. Thank you very much for clarifying this cryptic syntax.

    Kevin

    ReplyDelete
  9. Another equivalent is

    !function($){
    // code goes heer
    }(jQuery)

    ReplyDelete
  10. var test = (function($,thisModule) {
    // some function here ...
    // some function here ...
    // some function here ...
    return thisModule;
    }(jQuery, test || {} ));


    what does it means ???

    ReplyDelete