Examples of calling js anonymous functions (in various forms) and JavaScript Functions
An anonymous function is a function without a real name.
JavaScript anonymous functions have various forms and are easy to get confused.
The following are successfully called anonymous functions:
Copy codeThe Code is as follows:
(Function (){
Alert (3 );
})
();
(Function f1 (){
Alert (4 );
}) (); // It can be called without being an anonymous function !!
Void function (){
Alert ('void water ');
} (); // It is said that the efficiency is the highest. In Javascript, void is an operator that specifies to calculate an expression but does not return a value.
! Function (){
Alert ('! Water ');
} (); // Operator + anonymous function call
(Function (){
Alert ('water ');
} (); // Parentheses + anonymous functions, a bit forced to execute ~
Pay attention to common errors when using anonymous functions:
Copy codeThe Code is as follows:
// Incorrect syntax 1
(Function f1 (){
Alert (5 );
}) F1 (); // This is not an anonymous function!
// Incorrect syntax 2
(Function (){
Alert (6 );
}); // The syntax is correct. If no anonymous function is called, the call entry cannot be found because no name is available.
// Incorrect syntax 3
Function (){
Alert (1 );
} (); // Called if no reference to the function is generated
Note the role of parentheses.
Parentheses can combine our expressions into blocks, and each block, that is, each pair of parentheses, has a return value. The returned value is actually the return value of the expression in parentheses. Therefore, when we enclose anonymous functions with a pair of parentheses, in fact, parentheses return the Function object of an anonymous Function. Therefore, adding an anonymous function to the parentheses is like a function with a name, and we get its reference position. Therefore, if the parameter list is added after the referenced variable, the call form of the common function is implemented.
Anonymous functions in js
First, a large structure is an anonymous function. One of the forms of an anonymous function is like this. It is wrapped in parentheses and added to the end to call this anonymous function. The format is as follows:
(Function (){
......
})();
The advantage of writing this is that the variables inside are closed and not open to the outside, reducing the confusion caused by global variables.
For details, you can check the anonymous functions and closures.
How to call js anonymous Functions
Store anonymous functions in a variable.
Var a = function (){...};
A ();