HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How do you find out the caller function in JavaScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
youhowfunctionfindthecalleroutjavascript

Problem

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?

Solution

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


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

Code Snippets

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

Context

Stack Overflow Q#280389, score: 1080

Revisions (0)

No revisions yet.