function main()
{
   Hello();
}

function Hello()
{
  // How do you find out the caller function is 'main'?
}

有办法找到调用堆栈吗?


当前回答

你可以得到完整的堆栈跟踪:

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

对我来说很好,你可以在函数中选择你想要返回的程度:

function getCaller(functionBack= 0) {
    const back = functionBack * 2;
    const stack = new Error().stack.split('at ');
    const stackIndex = stack[3 + back].includes('C:') ? (3 + back) : (4 + back);
    const isAsync = stack[stackIndex].includes('async');
    let result;
    if (isAsync)
      result = stack[stackIndex].split(' ')[1].split(' ')[0];
    else
      result = stack[stackIndex].split(' ')[0];
    return result;
}

2018年更新

严格模式下禁止调用。下面是使用(非标准)错误堆栈的替代方案。

下面的函数似乎在Firefox 52和Chrome 61-71中完成了这项工作,尽管它的实现对这两种浏览器的日志格式做了很多假设,应该谨慎使用,因为它会抛出一个异常,并可能在完成之前执行两个正则表达式匹配。

'use strict'; const fnNameMatcher = /([^(]+)@|at ([^(]+) \(/; function fnName(str) { const regexResult = fnNameMatcher.exec(str); return regexResult[1] || regexResult[2]; } function log(...messages) { const logLines = (new Error().stack).split('\n'); const callerName = fnName(logLines[1]); if (callerName !== null) { if (callerName !== 'log') { console.log(callerName, 'called log with:', ...messages); } else { console.log(fnName(logLines[2]), 'called log with:', ...messages); } } else { console.log(...messages); } } function foo() { log('hi', 'there'); } (function main() { foo(); }());

你可以使用函数。调用方获取调用函数。旧的方法使用参数。Caller被认为是过时的。

下面的代码说明了它的用法:

function Hello() { return Hello.caller;}

Hello2 = function NamedFunc() { return NamedFunc.caller; };

function main()
{
   Hello();  //both return main()
   Hello2();
}

关于废参数的注释。打电话者:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/caller

功能。呼叫方为非标准:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller

使用严格模式开/关(JavaScript & TypeScript),如果(!)调用者存在,你可以尝试这个

console.log(`caller:${(new Error()).stack?.split('\n')[2].trim().split(' ')[1]}`)