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")) 

其他回答

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

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

我想在这里加上我的小提琴:

http://jsfiddle.net/bladnman/EhUm3/

我测试了chrome, safari和IE(10和8)。工作正常。只有一个函数是重要的,所以如果你被这个大小提琴吓到了,请阅读下面的内容。

注意: 有相当数量的我自己的“样板”在这把小提琴。如果你喜欢,你可以删除所有这些并使用split's。这只是我一直依赖的一套超级安全的功能。

还有一个“JSFiddle”模板在那里,我使用许多小提琴简单快速小提琴。

看起来这是一个相当解决的问题,但我最近发现,callee是不允许在“严格模式”,所以为了我自己的使用,我写了一个类,将从它被调用的路径。它是一个小型助手库的一部分,如果你想单独使用代码,请更改用于返回调用者堆栈跟踪的偏移量(使用1而不是2)。

function ScriptPath() {
  var scriptPath = '';
  try {
    //Throw an error to generate a stack trace
    throw new Error();
  }
  catch(e) {
    //Split the stack trace into each line
    var stackLines = e.stack.split('\n');
    var callerIndex = 0;
    //Now walk though each line until we find a path reference
    for(var i in stackLines){
      if(!stackLines[i].match(/http[s]?:\/\//)) continue;
      //We skipped all the lines with out an http so we now have a script reference
      //This one is the class constructor, the next is the getScriptPath() call
      //The one after that is the user code requesting the path info (so offset by 2)
      callerIndex = Number(i) + 2;
      break;
    }
    //Now parse the string for each section we want to return
    pathParts = stackLines[callerIndex].match(/((http[s]?:\/\/.+\/)([^\/]+\.js)):/);
  }

  this.fullPath = function() {
    return pathParts[1];
  };

  this.path = function() {
    return pathParts[2];
  };

  this.file = function() {
    return pathParts[3];
  };

  this.fileNoExt = function() {
    var parts = this.file().split('.');
    parts.length = parts.length != 1 ? parts.length - 1 : 1;
    return parts.join('.');
  };
}

由于之前的答案都不像我所寻找的那样(只得到最后一个函数调用者,而不是作为字符串或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();

function main()
{
   Hello();
}

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