In-depth analysis of the plus signs and exclamation points before JavaScript Functions, analysis of javascript
+ Function (){}();
The plus sign can also be replaced !,~ And other unary operators, the effect is equivalent:
(Function () {console. log ("Foo! ") ;}) (); // Or (function () {console. log (" Foo! ");}());
Without this plus sign, the parser considers the function as the beginning of a function declaration, and the following () will cause a syntax error. When the + sign is added before the function, it becomes a function expression, and a () is added after the function expression to become a function that is executed immediately.
Let's take a look at the role of the exclamation point in front of the js function:
I. JS function declaration form
Function fnA () {alert ('msg ');} // declarative function Definition
Ii. JS function expression form
Var func = function (agr1, arg2) {// create an anonymous function alert (arg1 + ''+ arg2 );}
Iii. Common Format of immediate execution after JS anonymous function declaration
(Function () {/* code */})();
Description
1. The first pair of parentheses in the function () {}) returns the Untitled function to the script, and then an empty pair of parentheses immediately executes the returned untitled function. The parameters in the brackets are anonymous function parameters.
2. use parentheses to wrap the definition function body. The parser will call the definition function in the form of a function expression. That is to say, any way to convert a function into a function expression can make the parser correctly call and define a function. And! Is one of them, and +-| has such a function.
3. The function is mainly used for anonymous and automatic execution.