Home >Web Front-end >JS Tutorial >Examples of calling js anonymous functions (various forms)_javascript skills
Anonymous functions are functions without actual names.
JavaScript’s anonymous functions come in various forms, and if you don’t understand them clearly, it’s easy to get confused by the code.
The following is the anonymous function that was successfully called:
(function f1() {
alert(4);
})(); //It can be called like this even if it is not an anonymous function! !
void function(){
alert('void water');
}();//It is said to be the most efficient. void is an operator in Javascript. This operator specifies to calculate an expression but does not return a value.
!function(){
alert('!water');
}(); //Operator anonymous function call
(function(){
alert('water');
}());//Parentheses Anonymous function, a bit forced execution~
//Wrong writing 2
(function () {
alert(6);
}); //There is no syntax error, there is no anonymous function called, and there is no chance to call it later, because there is no name and the calling entry cannot be found.
//Wrong writing 3
function () {
alert(1);
}();//Call without generating a reference to the function
Parentheses can divide our expression combination into blocks, and each block, that is, each pair of parentheses, has a return value. This return value is actually the return value of the expression in parentheses. Therefore, when we use a pair of parentheses to surround an anonymous function, what the pair of parentheses actually returns is a Function object of the anonymous function. Therefore, a pair of parentheses plus an anonymous function is referenced by us just like a named function. So if you add a parameter list after this reference variable, the calling form of an ordinary function will be achieved.