1, (function ($) {...}) (JQuery);
1), principle:
This is actually an anonymous function, as follows:
Function (ARG) {...}
This defines an anonymous function with a parameter of ARG
When calling a function, the parentheses and arguments are written after 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 a parameter of ARG, and calling this anonymous function as a parameter param
and (function ($) {...}) (jquery) is the same, the reason why only use $ in formal parameters is to not conflict with other libraries, so the argument with jquery
Equivalent to funtion output (s) {...};output (jQuery), or Var fn=function (s) {...}; FN (jQuery);
2), function ( very useful ):
The greatest benefit of this notation is the formation of closures. In (function ($) {...}) (jQuery) functions and variables defined internally can only be valid within this scope.
The concept of whether a function function or a private variable is formed. Like what:
[JavaScript]View PlainCopy
- var i=3;
- function init () {
- Alert ("outer init:" +i);
- }
- (function ($) {
- var i=2;
- function init () {
- Alert ("inner init:" +i);
- }
- Init ();
- }) (JQuery);
- Init ();
Execution Result:
Inner Layer Init:2
Outer Init:3
2, $ (function () {...}); JQuery (function ($) {...}); $ (document). Ready (function () {...})
These three roles are the same.
In JQuery, $ (function () {}) and (function ($) {}) (jquery), $ (document). The difference between ready (function () {}) and so on is explained in detail----reproduced