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);
thanks for clarifying that ! Always nice to really understand what your doing instead of just copy/pasting the codes :)
ReplyDeleteThanks 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.
ReplyDeleteHow do you use this? Sorry i'm very new to both Javascript and JQuery.
ReplyDeleteI'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
what a great moment sin?
ReplyDeleteHi, unfortunaltely, I don't understand the difference :(
ReplyDeleteI don't understand the meaning of the (jQuery) between parentheses at the end of the function.
Thanks
Great! Thank you very much.
ReplyDeletethanks for the clarification.
ReplyDeleteThanks for this post
ReplyDeleteThank you very much for clarifying this cryptic syntax.
ReplyDeleteKevin
Another equivalent is
ReplyDelete!function($){
// code goes heer
}(jQuery)
var test = (function($,thisModule) {
ReplyDelete// some function here ...
// some function here ...
// some function here ...
return thisModule;
}(jQuery, test || {} ));
what does it means ???
thx : )
ReplyDelete