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.

4

4 回答 4

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.

于 2013-08-15T08:50:56.177 回答
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.

于 2013-08-15T09:00:06.947 回答
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.

于 2013-08-15T08:52:55.233 回答
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?

于 2013-08-15T08:56:56.077 回答