If there is no need to explicitly call the function and let the function be executed when it is defined, how should it be written? Next, the implementation steps will be introduced in detail. Interested friends can learn about it
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
The code is as follows:
< ;head>
Say Hello
< ;/head>
<script> <br>//define function <br>function sayHello() <br>{ <br>alert("hello"); <br>} <br>//call function <br>sayHello(); <br></script>
But if not If I need to explicitly call a function so that it can be executed when it is defined, how should I write it?
2. Thought process
Judging from the above examples, if you are smart and combine the above usage conditions, you may think:
===》Since the function name is added after Can the previous pair be executed by adding a pair of braces after the function definition? Like the following:
The code is as follows:
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?
The code is as follows:
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
The code is as follows:
function sayHello()
{
alert("hello");
};
(1);
These two sentences have nothing to do with each other. The function still will 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 The corresponding code 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.
The code is as follows:
(function sayHello()
{
alert("hello");
}());
There is another way to write it, which is to remove the following curly brackets, as
The code is as follows:
(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,....