function main()
{
   Hello();
}

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

有办法找到调用堆栈吗?


当前回答

我可以在2021年使用这些,并获得从调用者函数开始的堆栈:

1. console.trace();
2. console.log((new Error).stack)

// do the same as #2 just with better view
3. console.log((new Error).stack.split("\n")) 

其他回答

我知道你提到了“在Javascript中”,但如果目的是调试,我认为使用浏览器的开发工具更容易。这是它在Chrome中的样子: 只需将调试器放置在您想要研究堆栈的位置。

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

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;
}
function main()
{
   Hello();
}

function Hello()
{
  new Error().stack
}

我会这样做:

function Hello() {
  console.trace();
}
function Hello() {
    alert(Hello.caller);
}