However, the two methods are different. When the parser loads data to the execution environment, the function declaration and function expression are not treated equally. The parser will first read the function declaration and make it available before executing any code; while the function expression must wait
When defining a function, we generally use the following two methods:
Define with function declaration:
123 |
Function sum (a, B) {returna + B ;} |
Define using function expressions:
123 |
Varsum = function (a, B) {returna + B ;} |
The call methods are the same:
For example, if "1 + 1" is equal to a few:
However, the two methods are different. When the parser loads data to the execution environment, the function declaration and function expression are not treated equally. The parser will first read the function declaration and make it available before executing any code; while the function expression must wait until the parser executes to its line of code, to be interpreted and executed.
Example:
1234 |
Alert (sum (1, 1); function sum (a, B) {returna + B ;} |
The above code can be executed normally. Before the code is executed, the parser reads and adds the function declaration to the execution environment by calling the function declaration escalation process. When you evaluate the code, the Javascript engine declares the functions for the first time and places them on the top of the source code tree. Therefore, even if the declared function code is placed behind the code that calls it, the Javascript engine can also promote the function declaration to the top. If the preceding function declaration is changed to a function expression as shown in the following example, an error occurs during execution.
1234 |
Alert (sum (1, 1); varsum = function (a, B) {returna + B ;} |
The above code produces an error during execution because the function is located in an initialization statement rather than a function declaration. In other words, before executing the statement where the function is located, the variable sum will not save references to the function, and the first line of code will not be executed because an error has occurred.
In general, except when the function can be accessed through variables, the syntax of function declaration and function expression is actually equivalent.