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:
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 () {...})
The effect of these three is the same, I need to use the first type, writing simple.
A function that executes after the document is loaded.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Go" jQuery with $ (function () {}) and (function ($) {}) (jquery), $ (document). The difference between ready (function () {}) is explained in detail