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'?
}
有办法找到调用堆栈吗?
当前回答
在ES6和Strict模式下,使用以下方法获取Caller函数
console.log((new Error()).stack.split("\n")[2].trim().split(" ")[1])
请注意,如果没有调用者或没有前一个堆栈,上面的代码行将抛出异常。相应的使用。
获取callee(当前函数名),使用:
console.log((new Error()).stack.split("\n")[1].trim().split(" ")[1])
其他回答
下面是一个函数来获得完整的stacktrace:
function stacktrace() {
var f = stacktrace;
var stack = 'Stack trace:';
while (f) {
stack += '\n' + f.name;
f = f.caller;
}
return stack;
}
由于之前的答案都不像我所寻找的那样(只得到最后一个函数调用者,而不是作为字符串或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();
注意,根据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());
}
如果你出于某种原因真的需要这个功能,希望它能跨浏览器兼容,不担心严格的东西,并且向前兼容,那么传递一个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
}
function Hello() {
alert(Hello.caller);
}