I spoke about anonymous functions when I organized the javascript introductory training PPT today.
Writing anonymous Functions
As the name suggests, it is a function without a name (⊙ ﹏ ⊙ B Khan ). Anonymous functions are usually used to control javascript scopes to effectively avoid global variables. The following four common anonymous functions are written:
Anonymous function 1
(Function (){
// Do something
}) (); Anonymous function method 2
! Function (){
// Do something
}();
Above! You can also write it as + ,!! .
The above two methods are commonly used. The following two methods are found on google and I have never used them (well, I'm out ).
Anonymous function syntax 3
(Function (){
// Do something
} (); Anonymous function syntax 4
Void function (){
// Do something
}();
On Weibo just now, @ Park Ling proposed that the three most secure methods of writing should not cause context errors after the compression tool is packaged and compressed. For example, if the following code is normal before compression, it is not normal after compression, so strict context is required; problem, and the third will not have similar problems:
Var a = function (){}
(Function (){
Alert (1 );
})();
In the above example, an error occurs. This is because function a will pass the anonymous function following it into function a as a parameter. This explains why someone is used to adding an anonymous function, this is to prevent the above issue from failing to strictly follow the javascript syntax.
Passing parameters of anonymous Functions
Anonymous functions can pass parameters in the following way:
(Function (win, doc ){
Var $ = function (id ){
Return doc. getElementById (id );
}
Win. $ =$;
}) (Window, document );
Recursion of anonymous Functions
To reference itself in an anonymous function, you must use arguments. callee. The following describes the concatenation implemented using an anonymous function.
(Function (n ){
If (n <= 0 ){
Return 1;
} Else {
Return n * arguments. callee (n-1 );
}
}) (4 );