views:

74

answers:

3

Hi There, I am reading up on creating custom jQuery plugins and am a little confused as to the meaning of the following syntax:

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

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

+4  A: 

The surrounding parentheses create an anonymous function to which the $ symbol references the global jQuery object.

$.fn.truncate - This means that you are extending the jQuery object to include a new function called truncate.
Usage $( '#someElement' ).truncate();

Jacob Relkin
+5  A: 

The following parameters with jQuery are just executing the anonymous function and passing in jQuery as the $ parameter. This ensures that $ = jQuery just incase window.$ doesn't equal jQuery.

Here is a rewrite of the code that might make more sense:

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

myFunc(jQuery);
Tom Brothers
+3  A: 

It is not safe to assume that $ is owned by the jQuery library. Some other javascript libraries/users may/do use that identifier for other purposes. However, jQuery is always the jQuery library (barring any evildoers).

This anonymous function handily and safely exposes the $ shortcut as jQuery by making it a local parameter to the anonymous function. Since parameters will override any globals only for the scope of a function this will not affect any other user/library code outside of it.

Finally, where the anonymous function is executed jQuery is passed in as the first paramter to fill $.

So when boiled down, this is just a shortcut taken by plugin developers so that they can safely and reliably use $; if you don't mind using jQuery everywhere instead then this is totally optional.

joshperry