Anonymous functions are functions without actual names. javaScript anonymous functions have various forms. The following lists anonymous functions without actual names.
JavaScript anonymous functions have various forms and are easy to get confused.
The following are successfully called anonymous functions:
The 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:
The 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.