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 at all?
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 at all?
A message from 2018 where accessing
caller
is forbidden:The following function seems to do the job in Firefox 52 and Chrome 61 though its implementation makes a lot of assumptions about the logging format of the two browsers and should not be used for anything temporary developer debugging given that it throws an exception and possibly executes two regex matchings before being done.
Note that this feature is non standard, from
Function.caller
:The following is the old answer from 2008, which is no longer supported in modern Javascript:
I usually use
(new Error()).stack
in Chrome. The nice thing is that this also gives you the line numbers where the caller called the function. The downside is that it limits the length of the stack to 10, 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, to view and debug later, so setting a breakpoint isn't of use since it will be hit thousands of times)
I would do this:
heystewart's answer and JiarongWu's answer both mentioned that the
Error
object has access to thestack
.Here's an example:
Different browsers shows the stack in different string formats:
Safari : Caller is: main@https://stacksnippets.net/js:14:8 Firefox : Caller is: main@https://stacksnippets.net/js:14:3 Chrome : Caller is: at main (https://stacksnippets.net/js:14:3) IE Edge : Caller is: at main (https://stacksnippets.net/js:14:3) IE : Caller is: at main (https://stacksnippets.net/js:14:3)
Most browsers will set the stack with
var stack = (new Error()).stack
. In Internet Explorer the stack will be undefined - you have to throw a real exception to retrieve the stack.Conclusion: It's possible to determine "main" is the caller to "Hello" using the
stack
in theError
object. In fact it will work in cases where thecallee
/caller
approach doesn't work. It will also show you context, i.e. source file and line number. However effort is required to make the solution cross platform.If you really need the functionality for some reason and want it to be cross-browser compatible and not worry for strict stuff and be forward compatible then pass a this reference: