Coder Perfect

In JavaScript, how do you find the caller function?

Problem

function main()
{
   Hello();
}

function Hello()
{
  // How do you find out the caller function is 'main'?
}

Is it possible to get a hold of the call stack?

Asked by Ray Lu

Solution #1

Note that this solution is deprecated and should no longer be used according to MDN documentation

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller
function Hello()
{
    alert("caller is " + Hello.caller);
}

This is a non-standard feature, according to Function.caller:

The old response from 2008, which is no longer supported in contemporary Javascript, is as follows:

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

Answered by Greg Hewgill

Solution #2

Using browser-specific JavaScript, you may find the whole stack trace. The good news is that someone has already done it; the project code may be found on GitHub.

But not all the news is good:

By the way, you may use: if you just want the name of the caller function (in most browsers, but not IE).

arguments.callee.caller.name

But keep in mind that this is the name that appears after the function keyword. I couldn’t proceed any further (even with Google Chrome) without acquiring the entire function’s code.

As well as summarizing the rest of the finest responses (by Pablo Cabrera, nourdine, and Greg Hewgill). The only cross-browser and really secure solution is:

arguments.callee.caller.toString();

This will display the caller function’s code. Unfortunately, that is not enough for me, which is why I provide you with StackTrace and caller function Name tips (although they are not cross-browser).

Answered by Mariano Desanze

Solution #3

I know you said “in Javascript,” but I think it’s easier to just utilize your browser’s developer tools for debugging. In Chrome, it appears like this: Simply place the debugger where you wish to look into the stack.

Answered by Phil

Solution #4

In Chrome, I normally use (new Error()).stack. The wonderful thing about this is that it also tells you what line the caller used to call the function. The disadvantage is that it restricts the stack size to ten items, which is why I came to this page in the first place.

(I’m using this to collect callstacks in a low-level constructor during execution for later viewing and debugging, thus setting a breakpoint isn’t useful because it’ll be touched thousands of times)

Answered by heystewart

Solution #5

The complete stacktrace is available here:

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

Until the caller is null, that is.

On recursive functions, this results in an unending loop.

Answered by ale5000

Post is based on https://stackoverflow.com/questions/280389/how-do-you-find-out-the-caller-function-in-javascript