1. Preface Functions need to be defined first and then used. This is basically an iron law of all programming languages.
Generally, we need to call a JavaScript function. The basic situation is to define it first and then call it. Look at an example
< ;title>Say Hello
<script> <br>//define function <br>function sayHello() <br>{ <br>alert("hello"); <br>} <br>//call function <br>sayHello(); <br></script>
But if you don’t need to explicitly call the function and let the function be executed when it is defined, how should you write it?
2. Thought process From the above examples, if you are smart and combine the above usage conditions, you may think:
===》Since the call is in the function Can it be executed by adding a pair of curly brackets after the function definition? Like the following:
function sayHello()
{
alert("hello");
}();
Unfortunately, the above writing method will report a js syntax error.
Because the Javascript parser parses the curly brackets into function statements instead of function expressions by default when the parser parses the global function or function internal function keyword.
In other words, the last pair of curly braces will be parsed by default into a function that lacks a name, and a syntax error message will be thrown because the function declaration requires a name.
===》 You may also be thinking, if I pass parameters in curly braces, will it be parsed into an expression?
function sayHello()
{
alert ("hello");
}(1);
Indeed, the error is gone. But the above writing method is equivalent to the effect of the following writing method
function sayHello ()
{
alert("hello");
};
(1);
These two sentences have nothing to do with each other, the function will still not be executed
3. Correct writing For JavaScript, statements cannot be included in brackets (), so at this point, when the parser parses the function keyword, it will It is parsed into a function expression, not a function declaration. Therefore, just enclose the entire code (including the function part and a pair of braces at the end) in braces.
(function sayHello()
{
alert("hello");
}());
There is another way to write it, which is to remove the following curly brackets, as
(function sayHello()
{
alert("hello");
})();
It is recommended to use the first method.
But many of the better js libraries currently use the second method.
For example: web graphics drawing: git, draw2d,....