Explain the immediate execution function in JS in detail

  • 2021-07-22 09:06:08
  • OfStack

1. Anonymous functions cannot be defined separately, and must be assigned or executed immediately, otherwise they will be defined as syntax errors by JS engine


function(){alert(dada);}
VM229:1 Uncaught SyntaxError: Unexpected token 

2. It can be called immediately after the function body with parentheses. This function must be a function expression, not a function declaration


function(){alert(123);}();
VM265:1 Uncaught SyntaxError: Unexpected token

3. You can precede a function with a symbol or wrap the function in parentheses to eliminate the function declaration


(function(){alert(123);})();
undefined

4. The safest way to eliminate the function declaration is to add parentheses, because the operation symbol will also operate with the return value of the function, causing unnecessary trouble

5. The parentheses that enclose the function expression can enclose the parameters or not, and the effect is 1


(function(){alert(123);}());
undefined

6. What the immediate execution function does: Create a scope space to prevent variable conflicts or overrides


Related articles: