Why every jquery plugin is wrapped (function ($) {}) (jQuery);

every time i see jQuery plugin as follows:

(function($) { $.fn.example = function(options) { return this.each(function() { return 'Example!'; }); } })(jQuery); 

I am curious about this function:

 (function($) { // ... })(jQuery); 

It's necessary? If so, why? And if not, what are the alternatives / benefits?

+4
source share
3 answers

This is done so that the plugin is in its area and does not interfere.

Many libraries use $ as their shortcut, so we pass jQuery and assign it as $ to make sure it does not interfere.

jQuery explains its use in its docs: http://docs.jquery.com/Plugins/Authoring

+4
source

Agreed with Rocket's comment. From http://docs.jquery.com/Plugins/Authoring :

But wait! Where is my amazing dollar sign that I know and love? It is still there, however, to make sure your plugin does not collide with other libraries that can use the dollar sign, it is best practice to pass jQuery to a self-start (close) function that maps to its dollar sign, so it cannot be overwritten by another library in the framework of its implementation.

It also helps to respect the global namespace / prevent pollution of the global namespace. If you don't try - for example, by assigning something to window - any variables you create will be stored locally for your function - and you don’t have to worry about naming conflicts with any other code - in other jQuery plugins or otherwise - including using $ .

+2
source

This is mainly done so that the plugin closes where the $ sign does not collide with the rest of the libraries used along the side.

0
source

Source: https://habr.com/ru/post/1388635/


All Articles