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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With