Home >Web Front-end >JS Tutorial >Comparison of several different ways of writing js self-executing functions_javascript skills

Comparison of several different ways of writing js self-executing functions_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:50:441208browse

It is often necessary for a function to execute itself, but unfortunately this way of writing is wrong:

Copy the code The code is as follows:

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.
Copy code The code is as follows:

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

Copy code The code is as follows:

(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:
Copy code The code is as follows:

var a=1
(function(){alert(1);}());


Method 2: Add brackets around the function

Copy the code The code is as follows:

(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.
Copy code The code is as follows:

!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:
Copy code Code As follows:

(function(){alert(1);}());
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn