Often requires a function to execute itself, but this is wrong:
Copy Code code as follows:
function () {alert (1);} ();
The reason is the first half "function () {alert (1);}" As a function declaration, not as a function expression, so that the following "();" Become isolated, resulting in grammatical errors.
According to the above analysis, this piece of code, although there is no syntax error, but also does not conform to our expectations, because this function does not run itself.
Copy Code code as follows:
function () {alert (1);} (1);
In summary, the crux of the problem is how to express that the code describes a function expression, not a function declaration statement.
The correct writing is varied and has its own advantages and disadvantages:
Method 1: The first and last parenthesis
Copy Code code as follows:
(function () {alert (1);} ());
This is the JSLint recommendation, the benefit of which is to remind the person reading the code that this code is a whole.
For example, in an editor with syntax highlighting, the last closing parenthesis is highlighted after the first opening parenthesis, and the person looking at the code can see the whole.
However, for some students who write code that does not like a semicolon after a row, some pits may be formed, such as the following code that will report a run-time error:
Copy Code code as follows:
var a=1
(function () {alert (1);} ());
Method 2:function outside Braces
Copy Code code as follows:
(function () {alert (1);}) ();
This approach is less of a code-integrity benefit than Method 1.
Method 3:function Front plus operator, common is! with void.
Copy Code code as follows:
!function () {alert (1);} ();
void function () {alert (2);} ();
Obviously, add "!" or "+" and other operators, is the simplest to write.
Plus "void" to knock five down the keyboard, but heard that there is a benefit is, than add "!" One less logical operation. ----I just heard, it's unclear, so.
Finally, on behalf of me personally, I strongly support Method 1, which is JSLint's recommended wording:
Copy Code code as follows:
(function () {alert (1);} ());