Often requires a function to self-execute, but this one is wrong:
function () {alert (1);} ();
The reason is the first half of the "function () {alert (1);}" is treated as a function declaration, not as a function expression, so that the following "();" Become isolated and produce grammatical errors.
According to the above analysis, this piece of code, although there is no grammatical error, but also does not conform to our expectations, because this function is not self-executing.
function () {alert (1);} (1);
The crux of the problem, however, is how to define the code that describes a function expression rather than a function declaration statement.
The correct wording is varied and has pros and cons:
Method 1: The first and last parentheses
(function () {alert (1);} ());
This is the JSLint recommendation, the advantage is, can remind the person reading the code, this code is a whole.
For example, in an editor with syntax highlighting matching, when the cursor is behind the first opening parenthesis, the last closing parenthesis is highlighted, and the person looking at the code can see the whole at a glance.
However, some of the students who write code do not like to add a semicolon after the line will also form some pits, for example, the following code will be reported to run the wrong:
var a=1
(function () {alert (1);} ());
Method 2:function outside parentheses
(function () {alert (1);}) ();
This approach is less of a code integrity benefit than Method 1.
The 3:function method is preceded by the operator, which is common with void.
!function () {alert (1);} ();
void function () {alert (2);} ();
Obviously, add "!" or "+" operators, it is easiest to write.
Plus "void" to knock five keyboard, but heard that there is a benefit is, than add "!" One less logical operation. ----I just heard that, unknown, so.
Finally, on behalf of my personal, strongly support Method 1, that is, the recommended wording of JSLint:
(function () {alert (1);} ());
Reprinted from: http://www.jb51.net/article/31078.htm
Comparison of several different ways of writing JS self-executing function