开发者

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

I am reading up on creating custom jQuery plugins and am a little confused as to the meaning of the following s开发者_高级运维yntax:

(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.


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜