Strange syntax for jQuery extension

I recently saw this code in another post ( jQuery Set cursor position in text area )

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

For too long, trying to figure out what it is doing, I finally realized that it just creates a new function with the $ parameter, and then calls it using jQuery as the parameter value.

So in fact, he just does this:

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

What is the reason for the original, more confusing version?

+5
source share
3 answers

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

$, . , , , . , , , , $.

+5

JavaScript $ , jQuery . $, jQuery . jQuery $.

, :

(function($) {
  // code using $ goes here
})(jQuery);
+3
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..
}
0
source

All Articles