How do you find out the caller function in JavaScript?

Ray Lu picture Ray Lu · Nov 11, 2008 · Viewed 469.5k times · Source
function main()
{
   Hello();
}

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

Is there a way to find out the call stack?

Answer

Greg Hewgill picture Greg Hewgill · Nov 11, 2008
function Hello()
{
    alert("caller is " + Hello.caller);
}

Note that this feature is non-standard, from Function.caller:

Non-standard
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.


The following is the old answer from 2008, which is no longer supported in modern Javascript:

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