The functions in JavaScript are actually objects, each of which is an instance of a function type, with properties and methods as with other reference types. Because the function is an object, the function name is actually a pointer to the function object, which is a reference to the function object, so a function can have multiple names.
1. How the function is defined:
1) Use function declarations to define functions:
function sum (num1,num2) {
return num1+num2;
}
2) define the function using the function expression: Define the variable sum and initialize it to a function, and the variable sum can refer to the function. Note that there is a semicolon at the end of the function, just like declaring a variable.
var sum = function (num1,num2) {
return num1+num2;
};
3) Define functions using function constructors (generally not recommended, although a good understanding of function object types)
The function constructor can receive any number of arguments, but the last parameter is treated as the body of the function, and the preceding parameters are treated as arguments to the new function.
var sum = new Function ("Num1", "num2", "return num1+num2");
Because this method defines a function, it results in parsing two of times of code (the first parsing is a script code, and the second is parsing the string passed into the constructor), which affects performance.
No function overloads exist in 2.script
If there are multiple functions with the same name, the following function overrides the previously defined function.
For example:
function Increnum (num) {
return num+10;
}
function Increnum (num) {
return num+20;
}
var result = Increnum (10);
alert (result);//30
The code above is the same as the following code:
var increnum = function (num) {return num+10};
Increnum = function (num) {return num+20};
Alert (Increnum (10));//30
3. The difference between a function declaration and a function expression:
When the parser loads data into the execution environment, the parsing order and timing of function declarations and function expressions are different. The parser first reads the function declaration so that it can be accessed before executing any code, and the expression must wait until the parser executes to the line of code it is in before it is actually executed.
Alert (sum (10,20));
function sum (num1,num2) {
return num1+num2;
}
The code above works as expected, because before executing the code, the parser reads the function declaration and adds it to the execution environment so that the function can be accessed. If you change the function declaration to a function expression, you will get an error.
Alert (sum (10,20));
var sum = function (num1,num2) {return num1+num2};
In addition to this distinction, general function declarations and function expressions are equivalent.
Functions in JavaScript (i)