Differences between the two defining function methods in javascript and the effect of function pre-compilation, javascript Compilation
We know that there are two ways to define functions in javascript:
Function mm (){}
This form declares a function. Like var declares a variable mechanism, the script performs pre-compilation before interpretation and execution.
Var mm = function (){}
This form assigns a value to a variable. Although it is also pre-compiled, it only allocates a memory space to the mm variable in advance without initialization.
Code 1:
Alert (a); // print the memory alert (B) of function a; // undefined alert (c); // JS returns the error "c" undefined function () {} var B = function (){};
Code 2:
func(); //2 func = function() {alert(1);}; func(); //1 function func() {alert(2);}; func(); //1
Visible:
Javascript is not fully interpreted in order, but is pre-compiled before interpretation ". For a function defined in the first method, javascript can be used before the function is defined. For a function defined in the second method, it cannot be used in advance because its value is undefined.
Different javascript function definitions
Section 1: new function uses the built-in function object to construct a function
Var sum = new function (a, B) is equivalent:
Function Anonymous class ();
Var sum = new anonymous class (a, B );
When you execute new, an instance has been created from the Function, and a and B do not exist,
Therefore, the output a + B is calculated based on the null values of the mathematical operation to get NaN.
The second paragraph: var sum = function (a, B) is equivalent to: function sum (a, B)
So we can output: AB;
JavaScript: function declaration and function expression
Javascript is a language for interpreting execution, but it is also pre-compiled.
If (condition) {function sayHi () {alert ("Hi! ") ;}} Else {function sayHi () {alert (" Yo! ");}}
In this form, the JS engine registers the method to the window object during the pre-compilation process, that is, window. sayHi.
The if else condition is not taken into account, causing repeated sayHi methods to be registered. In this case, the syntax is invalid.
Var sayHi; if (condition) {sayHi = function sayHi () {alert ("Hi! ") ;};} Else {sayHi = function sayHi () {alert (" Yo! ");};}
The following is a variable (rather than a function), which can be assigned repeatedly. Therefore, the syntax is normal.
I wonder if I have made it clear.