views:

48

answers:

3

I recently saw this code on another post ( http://stackoverflow.com/questions/499126/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?

+4  A: 

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.

zipcodeman
It also seems to be a very commonly used practice in jQuery plugins for preventing conflicts.
Corey Sunwold
A: 
new function($) {
    $.fn.setCursorPosition = function(pos) {
        // function body omitted, not relevant to question

       // You are safe to always use $ here 
    }
} (jQuery);

and

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

    // you have to make sure $ was not overwritten before using it here..
}
Reigel
+3  A: 

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);
Greg