Using jQuery Functions

I am not very familiar with jQuery and it works. Does anyone know what these statements are doing? (Btw. They wrap up all the .js content)

(function ($) { 'use strict' ... })(jQuery); (function () { 'use strict' ... })(); 

The second, I think, is an anonymous function declaration, so as not to make variables inside accessible outside.

I know that there is a ready-made function called when the DOM loads.

 $(function () { 'use strict' ... }); 

Although I can not understand what the first 2 functions do.

+4
source share
4 answers

They are self-starting functions that protect the scope.

Notice how the parameter (jQuery) is accepted as $ in the first function. That way you can use short syntax everywhere, while still working in non-conflict mode.

+4
source
 (function ($) { 'use strict' ... })(jQuery); 

This will make $ available only in the area of ​​the anonymous self-starting function, this means that $ will not pollute the global area, and it will ensure that $ jQuery . If other frameworks set their own $ (for example, a prototype), inside the closure of the $ function there would be jQuery , because jQuery is a passed parameter that will be called and accessible inside the function like $ . Local scope variables in JavaScript take precedence over the parent scope .

 (function () { 'use strict' ... })(); 

This is an anonymous self-consistency function, acting as a closure, usually to preserve local variables rather than leak them into the global scope.

+3
source
 (function ($) { 'use strict' ... })(jQuery); 

This one is used to make sure $ is in your jQuery code. There may be cases with other libraries or code that are overwritten by $. But this code ensures that $ is jQuery within the scope of functions.

Thus, the functional code in both cases is used for the scope functionality.

+1
source
 (function ($) { ... })(jQuery); 

You may think that this operator is divided into 2 parts, (function ($) { ... }) - create an anonymous function, (jQuery) calls an anonymous function, it looks like

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

some other library will also use $ (e.g. Zepto ), so by passing jQuery to param $ can be sure that $ refers to jQuery and this anonymous function can create a safe area for your statement.

And for 'use strict' you can read more about this: What does "use strict" do in JavaScript and what are the reasons for this?

0
source

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


All Articles