Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery use of functions [duplicate]

I'm not very familliar with jQuery and it's functions. Does anyone know what these declarations are doing? (Btw. they wrap the entire .js content)

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

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

The second I guess, is a declaration of an anonymus function to not make variables inside accessable from outside.

I know there's a ready function that is called when the DOM was loaded.

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

Though I can't figure out what the first 2 functions do.

like image 840
marcel Avatar asked Feb 16 '23 13:02

marcel


2 Answers

They are self-invoking functions, protecting the scope.

Note how the parameter (jQuery) is accepted as $ in the first function. In this way you can use the short-syntax everywhere, while still operating in a non-conflict mode.

like image 152
Maxim Krizhanovsky Avatar answered Feb 18 '23 10:02

Maxim Krizhanovsky


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

This will make $ available only in the scope of the self calling anonymous function, this means that $ will not pollute the global scope and it will make sure that $ is jQuery. If there were other frameworks setting their own $ (like prototype), inside the function closure $ will be jQuery because jQuery is the parameter passed in that will be named and available inside the function as $. Local scope variables in JavaScript have precedence over parent scope.

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

This is a self calling anonymous function acting as a closure, usually to keep variables scoped locally and not leak them to the global scope.

like image 29
Marco Bettiolo Avatar answered Feb 18 '23 09:02

Marco Bettiolo