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]);

其他回答

我试图用这个问题来解决这个问题和当前的奖励。

赏金要求在严格模式下获得调用者,我能看到的唯一方法是引用在严格模式外声明的函数。

例如,以下是非标准的,但已经用之前(2016年3月29日)和当前(2018年8月1日)版本的Chrome、Edge和Firefox进行了测试。

函数调用者() { 返回caller.caller.caller; } 使用严格的; main()函数 { //原来的问题: 你好(); //赏金问题: (function() {console.log('匿名函数调用' + caller().name);}) (); } 函数Hello () { //你如何发现调用函数是'main'? console.log('Hello calling by ' + caller().name); } main ();

只需控制台日志错误堆栈。这样你就可以知道你是如何被召唤的

Const hello = () => { console.log(新的错误('I was called').stack) } Const sello = () => { 你好() } 你可以()

在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]) 

如果你只想要函数名而不是代码,并且想要一个独立于浏览器的解决方案,请使用以下方法:

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,这就是为什么我首先来到这个页面。

(我使用这个在执行期间收集低级构造函数中的调用栈,以便稍后查看和调试,所以设置断点是没有用的,因为它将被命中数千次)