问题
I noticed that in some places, jQuery code is wrapped in a self-invoking function like below. Why is this done, in what cases is this useful and in what cases is an unnecessary boilerplate?
function( $ ) {
...
}( jQuery );
回答1:
The short answer: To prevent variable name conflicts. It is not always needed, but good practice in order to create conflict free reusable code.
The long answer: In javascript the $ symbol is just another variable. jQuery uses it because it is a nice shorthand instead of having to type out jQuery each time, but so can any other code (including other libraries).
To prevent conflict with other uses of a variable at the same scope (in this case $ at the "global" scope) it is common for code to be wrapped in a self-invoking function with the "conflict-free" variables passed as the function parameters. This then creates a new scope where your variable won't interfere with other uses of that variable. That way you can pass the full named variable & uses it with whatever name you want within the anonymous function.
So, when creating conflict free reusable code it is good practice to use this methodology:
(function( $ ) {
...
})( jQuery );
Along these lines you will also see the following format:
(function( $, window, undefined ) {
...
})( jQuery, window );
In this instance undefined
is simply used for readability to indicating that no more arguments are passed to the function.
回答2:
In case you want to avoid conflict regarding use of $
function( $ ) {
...
}( jQuery );
Inside this function you can use $
without having to worry about it's use outside of it as inside that function, $
always refers to the jQuery
object.
This is helpful while creating jQuery plugins,You will see jQuery plugin's use this kind of function to avoid conflicts with other plugins.
Reference :
http://learn.jquery.com/plugins/basic-plugin-creation/
回答3:
In function scope $
is local variable that not conflict with any other global $
.
来源:https://stackoverflow.com/questions/17319718/self-invoking-function-jquery