I believe that the two methods have been used by everyone, but not everyone may know the difference and Internal principles.
Copy codeThe Code is as follows:
// Method 1
Function func1 (x, y ){
// Your code
}
// Method 2
Var func2 = function (x, y ){
// Your code
}
Method 1 is a typical Function declaration ).
Method 2 is a Function expression that assigns an anonymous Function to a variable. Or create an anonymous function with the form parameter x and y in method 2, and assign the value to the variable func2.
The main difference is:
1. The specified function name to be displayed in the function declaration. Here it is func1. The function expression uses the anonymous function.
2. method 1 is loaded into the scope before Code Execution (Interpretation period), and method 2 is loaded at Code Execution (runtime ).
A simple example shows the differences in their usage.
Copy codeThe Code is as follows:
Alert (func1); // --> func1 source code
Alert (func2); // --> undefined
// Method 1
Function func1 (x, y ){
// Your code
}
// Method 2
Var func2 = function (x, y ){
// Your code
}
As you can see, the first pop-up is the source code of func1, but the second is undefined. That is, the method 1 (function declaration) is used to define a function. You can use it on the code of this function. If the method 2 (function expression) is used to define a function, it cannot be used before its definition, it can only be used after its definition.
It involves the Execution context and Activation object ). For more information, see EcmaScript 5.
Recently, more and more people prefer to use method 2 to define functions, especially nested functions. For example, simply defining a function is still a habit of method 1.