Home >Web Front-end >JS Tutorial >Immediate execution function in JS

Immediate execution function in JS

高洛峰
高洛峰Original
2017-02-25 16:10:201502browse

1. Anonymous functions cannot be defined separately and must be assigned or executed immediately, otherwise it will be defined as a syntax error by the JS engine

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

2. Add parentheses after the function body to call it immediately. The function form must be a function expression, not a function declaration

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

3. It can be used in the function Add a symbol in front of it, or wrap the function with 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 operator symbol It will also be calculated with the return value of the function, causing unnecessary trouble

5. The parentheses surrounding the function expression can include parameters or not, and the effect is the same

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

6. The role of the immediate execution function: Create a scope space to prevent variable conflicts or overwriting

Please pay attention to more articles related to the immediate execution function in JS PHP Chinese website!

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