Introduction and examples of caller and callee properties in js

  • 2020-03-30 03:17:25
  • OfStack

A caller,

Returns a reference to a function that calls the current function.

FunctionName. The caller

The functionName object is the name of the function being executed.

instructions

For functions, the caller property is defined only when the function executes. If the function is called from the top level of a Javascript program, the caller contains null.

The following example illustrates the use of the caller property:


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();


Second, the callee

Returns the body of the Function object being executed, that is, the specified Function object.

[function.] the arguments. The callee
The optional function parameter is the name of the currently executing function object.

instructions

The initial value of the callee property is the Function object being executed.

The callee property is a member of the arguments object and represents a reference to the function object itself, which is good for recursion of anonymous functions or for encapsulation of functions, such as the recursion in the following example to calculate the sum of natural Numbers from 1 to n. This property is only available when the relevant function is executing. It's also important to note that callee has a length property, which is sometimes good for validation. Arguments. Length is the argument length, and arguments. Callee. Length is the argument length, so you can tell if the argument length is the same as the argument length when called.

The sample


//Callee can print itself
function calleeDemo() {
     alert(arguments.callee);
}
//Used to validate parameters
function calleeLengthDemo(arg1, arg2) {
    if (arguments.length==arguments.callee.length) {
         window.alert(" Verify the shape parameter and argument length is correct! ");
        return;
     } else {
         alert(" Argument length: " +arguments.length);
         alert(" Shape parameter length:  " +arguments.callee.length);
     }
}
//The recursive calculation
var sum = function(n){
  if (n < = 0)                       
  return 1;
  else
    return n  + arguments.callee(n - 1)
}

More general recursive functions:


var sum = function(n){
    if (1==n) return 1;
else return n + sum (n-1);

Alert (sum(100));

Where the function contains a reference to sum itself, the function name is just a variable name, and the call to sum inside the function is equivalent to the call
A global variable is not a good representation of calling itself, so using callee is a good method.


Related articles: