Understanding the skeleton of the jQuery plugin

In the website, I found the following code to create a jQuery plugin:

(function($){ // Our code here... })(jQuery); 

I do not understand how this code works. I understand that the code runs immediately because the most recent () in function(){}() . Thus, all the code says that it is an anonymous function that starts immediately.

But I don’t understand why the wrapping needs to be passed to jQuery , and inside it requires $ .

From my understanding, $ is an alias of jQuery , which means almost the same thing. What is the meaning of $ and jQuery here? How does generic code work like a jQuery plugin?

+3
source share
4 answers

jQuery is the actual parameter. $ is a formal parameter. You could write very well:

 (function(ForAFewDollarsLess){ ForAFewDollarsLess('#myId') ... })(jQuery); 

One reason is convenience - short. Perhaps you are using jQuery in noConflict mode with other libraries. Maybe typing jQuery all the time is a hassle, or other plugins follow the bad methods and use $ instead of jQuery . In any case, you can use the self-start function as described above to solve the problem.

+3
source

You pass the $ alias in the function so that it always forwards JQuery. If there are some other libraries included in a specific page, for example a prototype that also uses $ , your code will not break and will work fine.

0
source

To be as compatible with other libraries as possible, jQuery offers .noConflict() . This removes the $ alias from the global namespace, so another library can use it if you want.

If you do not want your plugin to work with .noConflict() , it is not needed.

Using closure also allows you to not pollute the "global scope" var

0
source

Gnarf caused global pollution of the sphere, I would add functions.

You might want to use a helper function, for example:

 (function($){ // Our code here... $.fn.myPluginFunction = function () { ... var x = foobalizeTheFrobmaster(this.offset()) ... } function foobalizeTheFrobmaster(pos) { // do something useful return something; } })(jQuery); 

Thus, the internal function foobalizeTheFrobmaster() completely hidden in our closure.

0
source

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


All Articles