Can anyone explain what the syntax means when defining a jQuery plugin?

I read about creating custom jQuery plugins and got a little confused in the sense of the following syntax:

(function($){  
    $.fn.truncate = function() {  
        return this.each(function() { 
        });
     };
})(jQuery);

I understand that the function ($) is an anonymous function that accepts $. I just don’t quite understand why this function is enclosed in brackets and how the following brackets work with jQuery in them ....

0
source share
3 answers

It is unsafe to assume that it $belongs to the jQuery library. Some other javascript libraries / users may use this identifier for other purposes. However, jQueryit is always a jQuery library (with the exception of any villains).

$ jQuery, . , - / .

, , jQuery $.

, , , , $; jQuery , , .

+3

jQuery jQuery $. , $= jQuery incase. $ jQuery.

, :

function myFunc($) {   
 $.fn.truncate = function() {   
    return this.each(function() {   
 });   
}

myFunc(jQuery);
+5

The surrounding parentheses create an anonymous function by which the character $refers to the global object jQuery.

$.fn.truncate- This means that you are expanding the object jQueryto include a new function called truncate.
Using $( '#someElement' ).truncate();

+4
source

All Articles