Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird syntax for extending jQuery

I recently saw this code on another post ( jQuery Set Cursor Position in Text Area )

new function($) {
    $.fn.setCursorPosition = function(pos) {
        // function body omitted, not relevant to question
    }
} (jQuery);

After too long trying to understand what it was doing I finally figured out that it's just creating a new function with a parameter $ and then invoking it with jQuery as the parameter value.

So actually, it's just doing this:

jQuery.fn.setCursorPosition = function(pos) {
    // function body omitted, not relevant to question
}

What's the reason for the original, more confusing version?

like image 634
Brad Robinson Avatar asked Jun 10 '10 05:06

Brad Robinson


2 Answers

For large blocks of code using $ is much nicer than jQuery.

When using multiple libraries, people will often disable the $ shortcut because many libraries use it. Writing the code like that allows users to write code with the shortcut without worrying about conflicting with other libraries. And since this site applies to a wide audience, using that code is the most likely to work whether or not the user has $ enabled.

like image 72
zmbush Avatar answered Oct 19 '22 23:10

zmbush


Since other JavaScript libraries may use $ globally, your library should explicitly reference jQuery to prevent conflicts. By creating a function with parameter $, you can bind the jQuery object to that variable within the scope of that function. This gives you the safety of explicitly specifying the jQuery object AND the convenience of using the $ shorthand.

This is the pattern I am used to seeing:

(function($) {
  // code using $ goes here
})(jQuery);
like image 36
Greg Avatar answered Oct 20 '22 01:10

Greg