Some people are called "self-executing anonymous functions"
In closures, we often need to use anonymous functions, and I feel that closures are an anonymous function, a subset.
But calling a function directly behind an anonymous function can be an error. Like what:
function () { alert ("Hello iife");} ();
Uncaught syntaxerror:unexpected Token (
We expect the system to call this anonymous function immediately, but the system will assume that we are doing a function declaration and that the function declaration requires a function name. And the above is not, will be error.
Then we add a function name to it, and there is a small problem, as follows:
1 function f () {2 alert ("Iife"); 3 }(); 4 // uncaught syntaxerror:expected () to start arrow function, but got '; ' instead of ' = '
The expectation is that a named function expression is called immediately, and the result is that the function f is declared. The parentheses at the end are used as the grouping operator, and the expression must be supplied as a parameter
So how do we create a self-executing anonymous function? We can let the engine understand () the preceding is an expression rather than a function, such as:
(function () { alert ("Iife");}) (); // or (function () { alert ("Iife"); } ());
After we have added parentheses to the anonymous function and the parser resolves to the expression, we can also use this:
1[function () {}()];2 3~function () {}();4!function () {}();5+function () {}();6-function () {}();7 8 New function () {};9 New function () {}() ;Ten One vari =function () {}(); A -0,function () {}(); - true&&function() {}();
If you have anything to add, please leave a message, huh, da ~ ~ ~
The above contents refer to:
Source: Nanyi javascript:http://javascript.ruanyifeng.com/grammar/function.html#toc23
Source: The Cloud http://www.zhihu.com/question/20249179/answer/14487857
The function expression that is called immediately---iife