[Solved-6 Solutions] Find out caller function in javascript - javascript tutorial



Problem

How to find out the caller function in JavaScript ?

Solution 1:

This code checks the value a function's caller property.

function myFunc() {
  if (myFunc.caller == null) {
    return 'The function was called from the top!';
  } else {
    return 'This function\'s caller was ' + myFunc.caller;
  }
}

Solution 2:

Just console log your error stack.

const hello = () => {
  console.log(new Error('I was called').stack)
}
const sello = () => {
  hello()
}
sello()

Solution 3:

Try this:

function Hello()
{
    alert("caller is " + Hello.caller);
}
function Hello()
{
    alert("caller is " + arguments.callee.caller.toString());
}

Read Also

Call and apply

Solution 4:

You can use this code:

function Hello() {
    alert("caller is " + arguments.callee.caller.toString());
}

is equivalent to this:

function Hello() {
    alert("caller is " + Hello.caller.toString());
}

In case we decide to refactor the name of the invoked function (Hello), we would have to change all its occurrences.

Solution 5:

We can get the full stacktrace:

arguments.callee.caller
arguments.callee.caller.caller
arguments.callee.caller.caller.caller

Until caller is null.

It cause an infinite loop on recursive function.

Solution 6:

We can use Function.Caller to get the calling function. The following code illustrates its use:

function Hello() { return Hello.caller;}

Hello2 = function NamedFunc() { return NamedFunc.caller; };

function main()
{
   Hello();  //both return main()
   Hello2();
}

Related Searches to Find out caller function in javascript - javascript tutorial