If you do not need to display the called function and want it to be executed at the time of definition, how can you write it? Next, we will introduce the implementation steps in detail. If you are interested, let us know.
1. Preface
The function must be defined first and then used. This is basically an iron law for all programming languages.
In general, we need to call a JavaScript function. The basic situation is to define the function before calling it. Let's look at an example.
The Code is as follows:
Say Hello
Script
// Define function
Function sayHello ()
{
Alert ("hello ");
}
// Call function
SayHello ();
Script
However, if you do not need to display the call function and want this function to be executed during definition, how can you write it?
2. History of thinking
From the above examples, you may think about the following combination of the above usage conditions:
===Since the function name is called with a pair of braces after the function definition, can it be executed? As follows:
The Code is as follows:
Function sayHello ()
{
Alert ("hello ");
}();
Unfortunately, the preceding Writing Method reports a js syntax error.
Because when the Javascript parser parses the global function or function internal function keywords, the braces are parsed into function declarations by default, instead of function expressions.
That is to say, the last pair of braces will be parsed into a function without a name by default, and a syntax error message will be thrown, because the function Declaration requires a name.
You may think again, if I input a parameter in braces, will it be parsed into an expression?
The Code is as follows:
Function sayHello ()
{
Alert ("hello ");
} (1 );
Indeed, the error is gone. However, the above statement is equivalent to the following statement.
The Code is as follows:
Function sayHello ()
{
Alert ("hello ");
};
(1 );
The two statements are completely irrelevant and the function will not be executed.
3. Correct writing
For JavaScript, the arc () cannot contain statements. Therefore, when parsing the function keyword, the parser parses the corresponding code into a function expression, instead of function declaration, you only need to enclose all the code (including the function part and a pair of braces.
The Code is as follows:
(Function sayHello ()
{
Alert ("hello ");
}());
Another way to write is to remove the braces.
The Code is as follows:
(Function sayHello ()
{
Alert ("hello ");
})();
The first method is recommended.
However, many of the better js Libraries currently use the second method.
For example, for web graphics: git, draw2d ,....