A function self-execution is often required. Unfortunately, this method is incorrect:
Copy codeThe Code is as follows:
Function () {alert (1 );}();
The reason is that the first half of "function () {alert (1) ;}" is treated as a function declaration rather than a function expression, so that the subsequent" (); "becomes isolated, syntax error.
According to the above analysis, although this piece of code has no syntax error, it does not meet our expectation, because this function is not self-executed.
Copy codeThe Code is as follows:
Function () {alert (1) ;}( 1 );
To sum up, the crux of the problem is how to clearly describe the code as a function expression rather than a function declaration statement.
The correct syntax is diverse and has its own advantages and disadvantages:
Method 1: parentheses are added at the beginning.
Copy codeThe Code is as follows:
(Function () {alert (1 );}());
This is recommended by jslint. The advantage is that the Code is a whole piece of code that reminds people who read the code.
For example, in an editor with the syntax highlighting and matching function, when the cursor is behind the first left bracket, the last right bracket is highlighted. The person who looks at the code can see the whole at a glance.
However, for some students who do not like to add semicolons after writing code, there will also be some pitfalls. For example, the following code will report an error:
Copy codeThe Code is as follows:
Var a = 1
(Function () {alert (1 );}());
Method 2: brackets are added to the function.
Copy codeThe Code is as follows:
(Function () {alert (1 );})();
This method is less advantageous than method 1 in code integrity.
Method 3: add an operator before the function. A common one is! And void.
Copy codeThe Code is as follows:
! Function () {alert (1 );}();
Void function () {alert (2 );}();
Obviously, add "!" Or "+" operator, which is the simplest to write.
You need to press "void" on the keyboard five times, but I have heard that the advantage is that bid "! "Less than one logical operation. ---- I just heard that it's not clear.
Finally, I personally strongly support method 1, that is, jslint recommendation statement:
Copy codeThe Code is as follows:
(Function () {alert (1 );}());