1. (function ($) {...}) (JQuery);
1), principle:
This is actually an anonymous function, as follows:
Function (ARG) {...}
This defines an anonymous function with the argument arg
When calling a function, the parentheses and arguments are written behind the function, and because of the precedence of the operator, the function itself needs parentheses, namely:
(function (ARG) {...}) (param)
This is equivalent to defining an anonymous function with arg parameter, and calling this anonymous function as a parameter param
(function ($) {...}) (jquery) is the same, the reason that the only use of $ in formal parameters is to not conflict with other libraries, so the argument uses jQuery
Equivalent to funtion output (s) {...};output (jQuery); or Var fn=function (s) {...}; FN (jQuery);
2), function (very useful):
The greatest advantage of this writing is the formation of closures. In (function ($) {...}) (jQuery) functions and variables defined internally can only be valid in this scope.
the concept of whether a function function or a private variable is formed. For example:
var i=3;
function init () {
alert ("Outer init:" +i);
}
(function ($) {
var i=2;
function init () {
alert ("Inner layer init:" +i);
}
Init ();
}) (jQuery);
Init ();
Execution results:
Inner layer Init:2
outer Init:3
2, $ (function () {...}); JQuery (function ($) {...}); $ (document). Ready (function () {...})
These three functions are the same, I need to use the first one, simple writing.
The function to execute after the document is loaded.