I. caller
Returns a reference to the function that calls the current function.
FunctionName. caller
The functionName object is the name of the executed function.
Description
For a function, the caller attribute is defined only when the function is executed. If a function is called by the top-level Javascript program, caller contains null.
The following example illustrates the usage of caller attributes:
Copy codeThe Code is as follows:
Function callerDemo (){
If (arguments. caller ){
Var a = callerDemo. caller. toString ();
Alert ();
} Else {
Alert ("this is a top function ");
}
}
Function handleCaller (){
CallerDemo ();
}
HandleCaller ();
Function calleeDemo (){
Alert (arguments. callee );
}
CalleeDemo ();
Ii. callee
Returns the Function object being executed, that is, the body of the specified Function object.
[Function.] arguments. callee
The optional function parameter is the name of the currently executed Function object.
Description
The initial value of the callee attribute is the Function object being executed.
The callee attribute is a member of the arguments object. It indicates a reference to the function object itself. This facilitates recursion of anonymous functions or ensures function encapsulation, for example, the following example recursively calculates the sum of natural numbers from 1 to n. This attribute is only available when the related function is being executed. It should also be noted that callee has the length attribute, which is sometimes used for verification. Arguments. length is the length of the real parameter, and arguments. callee. length is the length of the form parameter, which can be used to determine whether the length of the form parameter is consistent with the actual length.
Example
Copy codeThe Code is as follows:
// Callee can print itself
Function calleeDemo (){
Alert (arguments. callee );
}
// Used to verify Parameters
Function calleeLengthDemo (arg1, arg2 ){
If (arguments. length = arguments. callee. length ){
Window. alert ("verify that the length of the form parameter and real parameter is correct! ");
Return;
} Else {
Alert ("real parameter length:" + arguments. length );
Alert ("parameter length:" + arguments. callee. length );
}
}
// Recursive Calculation
Var sum = function (n ){
If (n <= 0)
Return 1;
Else
Return n + arguments. callee (n-1)
}
Typical recursive functions:
Copy codeThe Code is as follows:
Var sum = function (n ){
If (1 = n) return 1;
Else return n + sum (n-1 );
Call time: alert (sum (100 ));
The function contains a reference to sum itself. The function name is only a variable name. Calling sum inside the function is equivalent to calling
A global variable cannot reflect the call itself. Using callee is a good method.