1. Preface
The function needs to be defined first and then used. This is basically the law of an iron in all programming languages.
In general, we need to invoke a JavaScript function, the basic condition is defined first, and then called. See an example
[HTML]View Plaincopy
- <!--by oscar999 2013-1-16-->
- <! 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>
But what if you don't need to show the calling function so that the function executes when it is defined?
[HTML]View Plaincopy
2. The process of thinking from the above example, smart you combined with the use of the above may be thinking: "= =" Since the time of the call is to add a pair after the function name and whether to add a pair of curly braces can be executed after the definition? Like the following:
[JavaScript]View Plaincopy
- function SayHello ()
- {
- Alert ("Hello");
- }();
Unfortunately, the above notation will quote JS syntax errors. Because the parser for JavaScript parses the global function or function key in the parser, the default is to parse the curly braces into a function declaration instead of a function expression. That is, the last pair of curly braces are parsed by default into a function that lacks a name, and a syntax error message is thrown because a function declaration requires a name.
= = = "You might think again, if I pass the argument in curly braces, will it parse into an expression?"
[JavaScript]View Plaincopy
- function SayHello ()
- {
- Alert ("Hello");
- } (1);
Indeed, the mistake is gone. But the above notation is equivalent to the effect of the following wording
[JavaScript]View Plaincopy
- function SayHello ()
- {
- Alert ("Hello");
- };
- (1);
The two sentences have absolutely nothing to do with the function.
3. Correct notation for JavaScript, parentheses () cannot contain statements, so at this point, when the parser parses the function keyword, it parses the corresponding code into a function expression instead of a function declaration
So, just wrap the curly braces around the code (including the function part and add a pair of curly braces to the back).
[JavaScript]View Plaincopy
- (function SayHello ()
- {
- Alert ("Hello");
- }());
Another way to do this is to remove the curly braces from the back, as
[JavaScript]View Plaincopy
- (function SayHello ()
- {
- Alert ("Hello");
- })();
The recommendation is to use the first way.
But now a lot of better JS library use is the second way.
For example: Web Graphics drawing: git, draw2d,....
4. Reference
1. http://benalman.com/news/2010/11/immediately-invoked-function-expression/
JS immediate execution of function expressions