function main()
{
Hello();
}
function Hello()
{
// How do you find out the caller function is 'main'?
}
有办法找到调用堆栈吗?
function main()
{
Hello();
}
function Hello()
{
// How do you find out the caller function is 'main'?
}
有办法找到调用堆栈吗?
当前回答
如果你只想要函数名而不是代码,并且想要一个独立于浏览器的解决方案,请使用以下方法:
var callerFunction = arguments.callee.caller.toString().match(/function ([^\(]+)/)[1];
注意,如果数组中没有[1]元素,那么上面的代码将返回错误。要解决这个问题,请使用以下方法:
var callerFunction = (arguments.callee.caller.toString().match(/function ([^\(]+)/) === null) ? 'Document Object Model': arguments.callee.caller.toString().match(/function ([^\(]+)/)[1], arguments.callee.toString().match(/function ([^\(]+)/)[1]);
其他回答
你可以使用函数。调用方获取调用函数。旧的方法使用参数。Caller被认为是过时的。
下面的代码说明了它的用法:
function Hello() { return Hello.caller;}
Hello2 = function NamedFunc() { return NamedFunc.caller; };
function main()
{
Hello(); //both return main()
Hello2();
}
关于废参数的注释。打电话者:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/caller
功能。呼叫方为非标准:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller
如果你出于某种原因真的需要这个功能,希望它能跨浏览器兼容,不担心严格的东西,并且向前兼容,那么传递一个this引用:
function main()
{
Hello(this);
}
function Hello(caller)
{
// caller will be the object that called Hello. boom like that...
// you can add an undefined check code if the function Hello
// will be called without parameters from somewhere else
}
下面是一个函数来获得完整的stacktrace:
function stacktrace() {
var f = stacktrace;
var stack = 'Stack trace:';
while (f) {
stack += '\n' + f.name;
f = f.caller;
}
return stack;
}
我通常使用(new Error())。堆叠在Chrome。 好处是,这还提供了调用者调用函数的行号。缺点是它将堆栈的长度限制在10,这就是为什么我首先来到这个页面。
(我使用这个在执行期间收集低级构造函数中的调用栈,以便稍后查看和调试,所以设置断点是没有用的,因为它将被命中数千次)
堆栈跟踪
您可以使用特定于浏览器的代码找到整个堆栈跟踪。好在已经有人成功了;这是GitHub上的项目代码。
但并非所有的消息都是好消息:
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: var Klass = function kls() { this.Hello = function() { alert(printStackTrace().join('\n\n')); }; } new Klass().Hello(); Google Chrome will alert ... kls.Hello ( ... but most browsers will expect a function name just after the keyword function and will treat it as an anonymous function. An not even Chrome will be able to use the Klass name if you don't give the name kls 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.
调用方函数名
顺便说一下,如果你只想要调用函数的名称(在大多数浏览器中,但不是IE),你可以使用:
arguments.callee.caller.name
但是请注意,这个名称将位于function关键字之后。我发现没有办法(甚至在谷歌Chrome上)在没有得到整个函数的代码的情况下得到更多。
调用方函数码
并总结了其他最好的答案(作者:Pablo Cabrera, nourdine和Greg Hewgill)。你可以使用的唯一跨浏览器且真正安全的东西是:
arguments.callee.caller.toString();
它将显示调用方函数的代码。遗憾的是,这对我来说还不够,这就是为什么我给你关于StackTrace和调用者函数Name的提示(尽管它们不是跨浏览器的)。