every time when I see a jQuery plugin like this:
(function($) {
$.fn.example = function(options) {
return this.each(function() {
return 'Example!';
});
}
})(jQuery);
I am wondering about the wrapping function:
(function($) {
// ...
})(jQuery);
Is it necessary? If yes, why? And if not, what are the alternatives/advantages?
It’s done this way to ensure the plugin is in its own scope and doesn’t interfere with anything.
A lot of libraries use
$as their shortcut, so we’re passingjQueryand assigning it as$to make sure it doesn’t interfere.jQuery explains its use in their docs: http://docs.jquery.com/Plugins/Authoring