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?
I'm attempting to address both the question and the current bounty with this question.
The bounty requires that the caller be obtained in strict mode, and the only way I can see this done is by referring to a function declared outside of strict mode.
For example, the following is non-standard but has been tested with previous (29/03/2016) and current (1st August 2018) versions of Chrome, Edge and Firefox.
If you are not going to run it in IE < 11 then console.trace() would suit.
Looks like this is quite a solved question but I recently found out that callee is not allowed in 'strict mode' so for my own use I wrote a class that will get the path from where it is called. It's part of a small helper lib and if you want to use the code standalone change the offset used to return the stack trace of the caller (use 1 instead of 2)
Here, everything but the
functionname
is stripped fromcaller.toString()
, with RegExp.StackTrace
You can find the entire stack trace using browser specific code. The good thing is someone already made it; here is the project code on GitHub.
But not all the news is good:
It is really slow to get the stack trace so be careful (read this for more).
You will need to define function names for the stack trace to be legible. Because if you have code like this:
Google Chrome will alert
... kls.Hello ( ...
but most browsers will expect a function name just after the keywordfunction
and will treat it as an anonymous function. An not even Chrome will be able to use theKlass
name if you don't give the namekls
to the function.And by the way, you can pass to the function printStackTrace the option
{guess: true}
but I didn't find any real improvement by doing that.Not all browsers give you the same information. That is, parameters, code column, etc.
Caller Function Name
By the way, if you only want the name of the caller function (in most browsers, but not IE) you can use:
But note that this name will be the one after the
function
keyword. I found no way (even on Google Chrome) to get more than that without getting the code of the whole function.Caller Function Code
And summarizing the rest of the best answers (by Pablo Cabrera, nourdine, and Greg Hewgill). The only cross-browser and really safe thing you can use is:
Which will show the code of the caller function. Sadly, that is not enough for me, and that is why I give you tips for the StackTrace and the caller function Name (although they are not cross-browser).
You can get the full stacktrace:
Until caller is
null
.Note: it cause an infinite loop on recursive functions.