① defining functions using function declaration syntax
1 function sum (num1,num2) {2 return num1+num2; 3 }
② defining functions using function expressions
1 var sum=function(num1,num2) {2 return num1+num2; 3 }
③ defining functions using function constructors
1 var sum=New Function (' num1 ', ' num2 ', ' return num1+num2 ');
There are three ways to define a function, where the second and third are technically part of a function expression, but it is not recommended to use the third method, which uses the function constructor, because the performance is lower than the first two methods. Regardless of the way the function is defined, the function is an instance of the type of functions and has properties and methods that are identical to other reference types. Here are three ways to define a function the only unequal price is that the second and third way defined functions do not have a function declaration promotion, the first way defined functions exist function declaration promotion (so-called function declaration promotion, that is, the parser in the execution environment loading data, will be the first to read the function declaration, and make it accessible before any code), other aspects are equivalent.
1 sum ($); // 3 2 3 function sum (num1,num2) {4 return num1+num2; 5 }
function declaration promotion exists in the way that function declaration syntax is used to define functions, so the SUM function executes normally.
1 sum ($); // Typeerror:sum is not a function 2 3 var sum=function(num1,num2) {4 return num1+num2; 5 }
A function expression is used to define the number of rows without a function declaration promotion, so an exception is reported.
1 sum ($); // Typeerror:sum is not a function 2 3 var sum=New Function (' num1 ', ' num2 ', ' return num1+num2 ');
There is no function declaration promotion in the way that functions are defined using the function constructor, so an exception is reported.
JavaScript Learning notes: 3 ways to define functions