JavaScript function definition
Define function
In JavaScript, the way to define a function is as follows:
function abs(x) {
if (x >= 0) { return x ;
} else { return -x;
}
}
The above abs() function is defined as follows:
function points out that this is A function definition; abs is the name of the function; the parameters of the function are listed in (x) brackets, and multiple parameters are separated by,; the code between {...} is the function body, which can contain several statements, or even without any statement.
Please note that when the statements inside the function body are executed, once the return is executed, the function will be executed and the result will be returned. Therefore, very complex logic can be implemented inside the function through conditional judgment and looping.
If there is no return statement, the result will be returned after the function is executed, but the result will be undefined.
Since a JavaScript function is also an object, the abs() function defined above is actually a function object, and the function name abs can be regarded as a variable pointing to the function.
Therefore, the second way to define a function is as follows:
var abs = function (x) {
if (x >= 0) { return x;
} else { return -x;
}
};
Function is one of the core of JavaScript language. Its basic syntax is as follows:##function functionName(arg0, arg1, ...) {
statements}
Grammar interpretation
Use the function keyword to define a function
The function keyword is followed by a space followed by the function name
The function name is followed by a pair of parentheses. arg0 and arg1 represent the parameters of the function. The parameters are separated by ",". The number of parameters can be 0-25 (0 means no parameters). When there are no parameters, the () brackets cannot be omitted. Parameters exceeding 25 will be ignored by JavaScript
{} is the function body, which contains the functional statements to be implemented by the function
Function expressionphp中文网(php.cn)
#JavaScript functions can be defined by an expression.
Function expressions can be stored in variables:
var x = function (a, b) {return a * b};
After the function expression is stored in the variable, the variable can also be used as a function:
php中文网(php.cn)
##Function Hoisting(Hoisting)
In the previous tutorial we have Learned about "hoisting". Hoisting is JavaScript’s default behavior of hoisting the current scope to the front. Hoisting is applied to variable declarations and function declarations. Therefore, the function can be called before declaration:myFunction(5);
function myFunction(y) {
return y * y;
}
arguments
JavaScript also has a free keyword arguments, which is only inside the function Works and always points to all parameters passed in by the caller of the current function.php中文网(php.cn)
php中文网(php.cn)