JavaScript function is a strange thing, in contact with a period of time you will be confused, do not understand what it is. Do you get confused by the fact that there are no names for JavaScript functions, and whether the JavaScript function is completely broken by the presence of an expression because the parameters of the JavaScript function are not typed? It is because of these annoyances that the JavaScript function is worth our inspiring, and I want to detail the function from the composition of the function, which sounds like a piece of crap, saying that anything is of course from composition to talk about, but because JavaScript functions you really can't fathom its shape, So here I'm going to elaborate on the composition of a standard function.
1. The name of the function
In object-oriented languages, functions generally have names, but JavaScript functions are not necessarily, such functions are called anonymous functions or the direct amount of functions. It's like an expression, and then the left value of the expression can be used to invoke a function, or it can be stored in a variable that is passed to another function. The advantage of this is that you don't have to create new objects every time you call.
Copy Code code as follows:
var f= function (x) {return x*x;};
Alert (f (6));
The above example will pop up the window on the page to show 36
2. Parameter
JavaScript function parameters are also more magical, when invoking JavaScript functions, if the parameters and functions defined by the parameters are inconsistent (for example, the number of inconsistencies), the program will not error, and sometimes even call success, which is unimaginable for the Java language, But JavaScript functions can do that. For example, the above example, we call this:
Copy Code code as follows:
The result is still 36. While this will not be an error, we still want the function to be called correctly, guaranteeing that the call is consistent with the number of parameters defined by the function. The arguments object allows you to get the number of arguments for a function caller. Modify the above code.
Copy Code code as follows:
var f= function (x) {
if (arguments.length>1) {
Return ' out of range ';
} else {
return x*x;
}
};
Alert (f (6,7));
Processing gets the number of arguments for the function caller, and you can also get the values of those parameters, and then modify the code again:
Copy Code code as follows:
var f= function (x) {
if (arguments.length>1) {
return arguments[0]*arguments[1];
Copy Code code as follows:
} else {
return x*x;
}
};
Alert (f (6,7));
Can you guess how much the result is? Yes, it's 42.