1. Foreword
The function needs to be defined first and then used. This is basically an iron law of all programming languages.
In general, we need to call a JavaScript function, and the basic situation is defined first and then called again. Look at an example
Copy Code code as follows:
<!--by oscar999 2013-1-16-->
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>say hello</title>
<body>
<script>
define function
function SayHello ()
{
Alert ("Hello");
}
Call function
SayHello ();
</script>
</body>
But what if you don't need to show the calling function, and let the function execute when it's defined?
2. The course of thinking
From the above example, you may want to combine the above with the following situations:
= = Is it possible to perform a call after the function name plus a pair of curly braces followed by a functional definition? Like the following:
Copy Code code as follows:
function SayHello ()
{
Alert ("Hello");
}();
Unfortunately, the above wording will quote JS syntax errors.
Because the JavaScript parser resolves the global function or function intrinsic function keyword in the parser, the braces are parsed into function declarations instead of function expressions by default.
That is, the last pair of braces is parsed by default to a function with a missing name, and a syntax error message is thrown because the function declaration requires a name.
= = = You might think again, if I passed the argument in curly braces, would it parse into an expression?
Copy Code code as follows:
function SayHello ()
{
Alert ("Hello");
} (1);
Indeed, there is no mistake. But the above wording is equivalent to the following writing effect
Copy Code code as follows:
function SayHello ()
{
Alert ("Hello");
};
(1);
The two sentences have nothing to do with the function still does not execute
3. The correct wording
For JavaScript, parentheses () cannot contain statements, so at this point, the parser resolves the function keyword by parsing the corresponding code into a function expression rather than a function declaration, so just enclose the braces in the code ( Include the part of the function and the following plus a pair of curly braces.
Copy Code code as follows:
(Function SayHello ()
{
Alert ("Hello");
}());
Another way to do that is to move the curly braces back out, as
Copy Code code as follows:
(Function SayHello ()
{
Alert ("Hello");
})();
Recommendation is to use the first method.
But at present a lot of better JS library use is the second way.
For example: Web Graphics drawing: git, draw2d,....