Javascript function is a rather strange thing. If you have been exposed to it for a while, you will be confused and unable to figure out what it is. Are you confused because some JavaScript functions have no names? Are you going crazy because the parameters of JavaScript functions have no types? Are you completely collapsed because JavaScript functions exist in the form of expressions? It is precisely because of these troubles that JavaScript functions are worthy of our consideration. I want to explain the function in detail from the composition of the function. This sounds like nonsense. Of course, when talking about anything, we should talk about it from the composition, but because of the JavaScript function, you do I can't figure out its shape, so here I will explain it in detail from the composition of a standard function.
1. Function name
In object-oriented languages, functions generally have names, but not necessarily for JavaScript functions. Such functions are called anonymous functions or function literals. It is like an expression, and then the lvalue of this expression can be used to call a function, or it can be stored in a variable and passed to other functions. Its advantage is that it does not need to create a new object every time it is called.
var f= function (x) {return x*x ;};
alert( f(6) );
The above example will pop up a window on the page to display 36
2. Parameters The parameters of the JavaScript function are also quite magical. When calling the JavaScript function, if the parameters filled in are inconsistent with the parameters defined by the function (for example, the number is inconsistent), the program will not error, and sometimes the call can even be successful. This is unimaginable for the Java language. , but javascript functions can do it. For example, in the above example, we call it like this:
alert(f (6,7))
The result is still 36. Although this will not go wrong, we still want the function to be called correctly to ensure that the number of parameters defined by the function is consistent with the call. The number of parameters of the function caller can be obtained through the Arguments object. Modify the above code.
var f= function (x) {
if (arguments.length>1) {
return "out of range";
} else {
return x*x;
}
};
alert( f(6, 7) );
deals with obtaining the number of parameters of the function caller, and can also obtain the values of these parameters. Modify the above code again:
var f= function (x) {
if(arguments.length>1) {
return arguments[0]*arguments[1];
} else {
return x*x;
}
};
alert( f(6,7) );
Can you Can you guess what the result is? Yes, it's 42.