It is often necessary for a function to execute itself, but unfortunately this way of writing is wrong:
function(){alert(1);}();
The reason is that the first half of "function(){alert(1);}" is regarded as a function declaration instead of A function expression, which makes the following "();" become isolated and cause a syntax error.
According to the above analysis, although this piece of code has no grammatical errors, it does not meet our expectations because this function does not execute itself.
function(){alert(1);}(1 );
To sum up, the crux is how to make it clear that the code describes a function expression rather than a function declaration statement.
There are many correct ways to write, each with its own pros and cons:
Method 1: Add brackets first and last
(function(){alert(1);}());
This is the writing method recommended by jslint. The advantage is that it reminds people who read the code that this code is a whole.
For example, in an editor with a syntax highlighting matching function, when the cursor is behind the first left bracket, the last right bracket will also be highlighted, and people looking at the code can see the whole thing at a glance.
However, for some students who don’t like to add semicolons after lines when writing code, there will also be some pitfalls. For example, the following code will report a run error:
var a=1
(function(){alert(1);}());
Method 2: Add brackets around the function
(function(){alert(1);})();
This approach has one less code integrity benefit than method 1.
Method 3: Add operator before function, the common ones are ! and void.
!function(){alert(1);}( );
void function(){alert(2);}();
Obviously, adding operators such as "!" or " " is the simplest to write of.
It takes five keystrokes to add "void", but I heard that one advantage is that it requires one less logical operation than adding "!". ----I just heard about it, I don’t know why.
Finally, on my personal behalf, I strongly support method 1, which is the recommended way of writing jslint:
(function(){alert(1);}());