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
直到调用者为空。
注意:它会导致递归函数的无限循环。
如果你只想要函数名而不是代码,并且想要一个独立于浏览器的解决方案,请使用以下方法:
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]);
我通常使用(new Error())。堆叠在Chrome。 好处是,这还提供了调用者调用函数的行号。缺点是它将堆栈的长度限制在10,这就是为什么我首先来到这个页面。
(我使用这个在执行期间收集低级构造函数中的调用栈,以便稍后查看和调试,所以设置断点是没有用的,因为它将被命中数千次)
注意,根据MDN文档,此解决方案已弃用,不应再使用
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller
function Hello()
{
alert("caller is " + Hello.caller);
}
注意,这个特性不是标准的,来自Function.caller:
非标准的 这个特性是非标准的,不在标准轨道上。不要在面向Web的生产站点上使用它:它并不适用于每个用户。实现之间也可能存在很大的不兼容性,将来行为可能会发生变化。
以下是2008年的旧答案,在现代Javascript中不再支持:
function Hello()
{
alert("caller is " + arguments.callee.caller.toString());
}
由于之前的答案都不像我所寻找的那样(只得到最后一个函数调用者,而不是作为字符串或callstack的函数),我在这里为那些像我一样的人发布了我的解决方案,希望这对他们有用:
function getCallerName(func) { if (!func) return "anonymous"; let caller = func.caller; if (!caller) return "anonymous"; caller = caller.toString(); if (!caller.trim().startsWith("function")) return "anonymous"; return caller.substring(0, caller.indexOf("(")).replace("function",""); } // Example of how to use "getCallerName" function function Hello(){ console.log("ex1 => " + getCallerName(Hello)); } function Main(){ Hello(); // another example console.log("ex3 => " + getCallerName(Main)); } Main();