Home >Web Front-end >JS Tutorial >Examples of calling js anonymous functions (various forms)_javascript skills

Examples of calling js anonymous functions (various forms)_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:39:101141browse

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:

Copy code The code is as follows:

(function () {
alert(3);
})
();

(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~


When using anonymous functions, you should also pay attention to common mistakes:
Copy code The code is as follows:

//Wrong writing 1
(function f1() {
alert(5);
})f1(); //This is no longer an anonymous function!

//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


Also pay attention to understand the role of parentheses.

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn