4

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.

marcel
  • 3,231
  • 8
  • 43
  • 76

4 Answers4

4

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.

Maxim Krizhanovsky
  • 26,265
  • 5
  • 59
  • 89
  • Thanks alot, I guess I finally got it. So if I'd use a global variable like this: var app = {}; and I put the self-invoking function below: (function(){ app.myString = ""; })(); the variable myString is put into app right after the script was loaded, and I can access it where ever I want ... right? – marcel Aug 15 '13 at 09:09
3
(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.

Marco Bettiolo
  • 5,071
  • 6
  • 30
  • 35
1
(function ($) { 'use strict' ... })(jQuery);

This one is used to make sure that $ in your code is jQuery. There might be cases with other libraries or code that $ gets overwritten. But this code ensures that $ is jQuery within the function scope.

So the function code in both cases is used to scope functionality.

JohanSellberg
  • 2,423
  • 1
  • 21
  • 28
0
(function ($) { ... })(jQuery);

You can think this statement split to 2 part, (function ($) { ... }) is to create an anonymous function, (jQuery) is call the anonymous function, this is similar to

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

some other library also will use the $ (like Zepto), so passing jQuery to param $ can be sure $ refer to jQuery, and this anonymous function can create a safe scope for your statement.

And for 'use strict' you can read more about it on: What does “use strict” do in JavaScript, and what is the reasoning behind it?

Community
  • 1
  • 1
Steely Wing
  • 16,239
  • 8
  • 58
  • 54