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.
<!--by oscar999 2013-1-16--><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
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:
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?
function sayHello(){alert("hello");}(1);
Indeed, the error is gone. However, the above statement is equivalent to the following statement.
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 () clause cannot contain statements. Therefore, when parsing the function keyword, the parser parses the corresponding code into a function expression instead of a function declaration.
Therefore, you only need to enclose all the code (including the function part and a pair of braces.
(function sayHello(){alert("hello");}());
Another way to write is to remove the braces.
(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 ,....
4. Reference 1. http://benalman.com/news/2010/11/immediately-invoked-function-expression/
Previous Article: [one of the Web chart series] comparison of SVG, VML, and HTML5 canvas Technology for drawing Web Images
Next article: Introduction to arguments, caller and callee in Javascript
-
Top
-
0
-
Step on
-
0