Since the function of JavaScript is also an object, the abs() function defined above is actually a function object, and the functions name abs can be considered as a variable pointing to the function.
var function (x) { if (x >= 0) { return x; Else { return -x; }};
这种方式下,function (x) { ... }是一个匿名函数,它没有函数名。但是,这个匿名函数赋值给了变量abs,所以,通过变量abs就可以调用该函数。
abs()//返回NaN
abs(x)the parameters of the function are received at this time x undefined , and the computed result is NaN .
To avoid receipt undefined , you can check the parameters:
function ABS (x) { if (typeof x!== ' number ') { throw ' not a number ';
} if (x >= 0) { return x; Else { return -x; }}
Arguments
JavaScript also has a free keyword arguments that works only inside the function and always points to all parameters passed in by the caller of the current function. argumentssimilar Array but it is not a Array :
function foo (x) { // tenfor (var i=0; i<arguments.length; i++) { c10/>// ten, }}foo (10, 20, 30);
Using arguments , you can get all the parameters that the caller passed in. That is, even if the function does not define any parameters, it can get the value of the parameter:
function abs () { if (arguments.length = = = 0) { return 0; } var x = arguments[0]; return x >= 0? X:-/ /0// // 9
In fact arguments , it is most commonly used to determine the number of incoming parameters. You may see the following notation:
// foo (a[, b], c) // receives two or three parameters, B is an optional parameter, and if only 2 parameters are passed, B defaults to null: function Foo (A, B, c) { if (arguments.length = = = 2) { // The actual parameters obtained are A and B, C for undefined // assign B to c null// B to default value } // ...}
Rest parameters
The ES6 standard introduces rest parameters
function Foo (A, B, ... rest) { Console.log (' a = ' + a); Console.log (' b = ' + b); Console.log (rest);} Foo (1, 2, 3, 4, 5);
JS function definition and invocation