function main()
{
   Hello();
}

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

有办法找到调用堆栈吗?


当前回答

注意,不能使用Function。Node.js中的caller,使用caller-id包代替。例如:

var callerId = require('caller-id');

function foo() {
    bar();
}
function bar() {
    var caller = callerId.getData();
    /*
    caller = {
        typeName: 'Object',
        functionName: 'foo',
        filePath: '/path/of/this/file.js',
        lineNumber: 5,
        topLevelFlag: true,
        nativeFlag: false,
        evalFlag: false
    }
    */
}

其他回答

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

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;
}

注意,根据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());
}

概括一下(并说得更清楚)…

这段代码:

function Hello() {
    alert("caller is " + arguments.callee.caller.toString());
}

等价于:

function Hello() {
    alert("caller is " + Hello.caller.toString());
}

显然,第一部分更容易移植,因为你可以改变函数的名字,从“Hello”说成“Ciao”,但仍然可以让整个程序正常工作。

在后一种情况下,如果你决定重构被调用函数的名称(Hello),你将不得不改变它的所有出现:

如果你出于某种原因真的需要这个功能,希望它能跨浏览器兼容,不担心严格的东西,并且向前兼容,那么传递一个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
}

你可以使用函数。调用方获取调用函数。旧的方法使用参数。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