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.
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,jQueryis 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
jQueryis 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 usingjQueryeverywhere instead then this is totally optional.