1. Caller
Returns a reference to the function that calls the current function.
functionName.caller
The functionName object is the name of the executed function.
illustrate
For functions, the caller attribute is only defined when the function is executed. If the function is called by the top level of a Javascript program, then the caller contains null.
The following example illustrates the usage of the caller attribute:
The code copy is as follows:
function callerDemo() {
if ( arguments.caller) {
var a= callerDemo.caller.toString();
alert(a);
} else {
alert("this is a top function");
}
}
function handleCaller() {
callerDemo();
}
handleCaller();
function calleeDemo() {
alert(arguments.callee);
}
calleeDemo();
2. 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 Function object currently executing.
illustrate
The initial value of the callee property is the Function object being executed.
The callee property is a member of the arguments object, which represents a reference to the function object itself, which is conducive to the recursion of anonymous functions or to ensure the encapsulation of the function. For example, the recursive calculation of the sum of natural numbers from 1 to n in the following example. This property is only available when the relevant function is being executed. It is also important to note that callee has the length attribute, which is sometimes better for verification. arguments.length is the length of the actual parameter, and arguments.callee.length is the length of the formal parameter. This can be used to determine whether the length of the formal parameter is consistent with the length of the actual parameter when calling.
Example
The code copy 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 formal parameters and actual parameters are correct!");
return;
} else {
alert("Real argument length:" +arguments.length);
alert("Size length: " +arguments.callee.length);
}
}
//Recursive calculation
var sum = function(n){
if (n < = 0)
return 1;
else
return n +arguments.callee(n - 1)
}
A more general recursive function:
The code copy is as follows:
var sum = function(n){
if (1==n) return 1;
else return n + sum (n-1);
When called: alert(sum(100));
The function contains a reference to the sum itself. The function name is just a variable name. Calling sum inside the function is equivalent to calling
A global variable cannot be well reflected in the call itself, and using callee will be a better method at this time.