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'?
}
有办法找到调用堆栈吗?
当前回答
在这里,除了函数名之外的所有内容都被RegExp从caller.toString()中剥离。
<!DOCTYPE html>
<meta charset="UTF-8">
<title>Show the callers name</title><!-- This validates as html5! -->
<script>
main();
function main() { Hello(); }
function Hello(){
var name = Hello.caller.toString().replace(/\s\([^#]+$|^[^\s]+\s/g,'');
name = name.replace(/\s/g,'');
if ( typeof window[name] !== 'function' )
alert ("sorry, the type of "+name+" is "+ typeof window[name]);
else
alert ("The name of the "+typeof window[name]+" that called is "+name);
}
</script>
其他回答
你可以得到完整的堆栈跟踪:
arguments.callee.caller
arguments.callee.caller.caller
arguments.callee.caller.caller.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
}
我通常使用(new Error())。堆叠在Chrome。 好处是,这还提供了调用者调用函数的行号。缺点是它将堆栈的长度限制在10,这就是为什么我首先来到这个页面。
(我使用这个在执行期间收集低级构造函数中的调用栈,以便稍后查看和调试,所以设置断点是没有用的,因为它将被命中数千次)
我知道你提到了“在Javascript中”,但如果目的是调试,我认为使用浏览器的开发工具更容易。这是它在Chrome中的样子: 只需将调试器放置在您想要研究堆栈的位置。
我想在这里加上我的小提琴:
http://jsfiddle.net/bladnman/EhUm3/
我测试了chrome, safari和IE(10和8)。工作正常。只有一个函数是重要的,所以如果你被这个大小提琴吓到了,请阅读下面的内容。
注意: 有相当数量的我自己的“样板”在这把小提琴。如果你喜欢,你可以删除所有这些并使用split's。这只是我一直依赖的一套超级安全的功能。
还有一个“JSFiddle”模板在那里,我使用许多小提琴简单快速小提琴。