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'?
}
有办法找到调用堆栈吗?
当前回答
我想在这里加上我的小提琴:
http://jsfiddle.net/bladnman/EhUm3/
我测试了chrome, safari和IE(10和8)。工作正常。只有一个函数是重要的,所以如果你被这个大小提琴吓到了,请阅读下面的内容。
注意: 有相当数量的我自己的“样板”在这把小提琴。如果你喜欢,你可以删除所有这些并使用split's。这只是我一直依赖的一套超级安全的功能。
还有一个“JSFiddle”模板在那里,我使用许多小提琴简单快速小提琴。
其他回答
使用严格模式开/关(JavaScript & TypeScript),如果(!)调用者存在,你可以尝试这个
console.log(`caller:${(new Error()).stack?.split('\n')[2].trim().split(' ')[1]}`)
在这里,除了函数名之外的所有内容都被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更安全。调用自参数。不赞成调用…
下面是一个函数来获得完整的stacktrace:
function stacktrace() {
var f = stacktrace;
var stack = 'Stack trace:';
while (f) {
stack += '\n' + f.name;
f = f.caller;
}
return stack;
}
试着访问这个:
arguments.callee.caller.name