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.
Copy codeThe Code is as follows:
<! -- By oscar999 -->
<! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> Say Hello </title>
</Head>
<Body>
<Script>
// Define function
Function sayHello ()
{
Alert ("hello ");
}
// Call function
SayHello ();
</Script>
</Body>
</Html>
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:
Copy codeThe 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?
Copy codeThe Code is as follows:
Function sayHello ()
{
Alert ("hello ");
} (1 );
Indeed, the error is gone. However, the above statement is equivalent to the following statement.
Copy codeThe 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.
Copy codeThe Code is as follows:
(Function sayHello ()
{
Alert ("hello ");
}());
Another way to write is to remove the braces.
Copy codeThe 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 ,....