function main()
{
   Hello();
}

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

有办法找到调用堆栈吗?


当前回答

据我所知,我们有两种方法从给定的资源中得到

arguments.caller whoCalled()函数 { 如果参数。Caller == null) console.log('我是从全局作用域调用的。'); 其他的 console.log(参数。Caller + '打电话给我!'); } Function.caller myFunc()函数 { 如果(myFunc。调用者== null) { 返回'函数是从顶部调用的!'; } 其他的 { 返回'这个函数的调用者是' + myfuncc .caller; } }

我想你已经有答案了:)。

其他回答

我会这样做:

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

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

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

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

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

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

function main()
{
   Hello();
}

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

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

看起来这是一个相当解决的问题,但我最近发现,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('.');
  };
}