function main()
{
   Hello();
}

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

有办法找到调用堆栈吗?


当前回答

你可以使用调试器;在功能上。 打开inspect元素和watch调用堆栈;

其他回答

试试下面的代码:

function getStackTrace(){
  var f = arguments.callee;
  var ret = [];
  var item = {};
  var iter = 0;

  while ( f = f.caller ){
      // Initialize
    item = {
      name: f.name || null,
      args: [], // Empty array = no arguments passed
      callback: f
    };

      // Function arguments
    if ( f.arguments ){
      for ( iter = 0; iter<f.arguments.length; iter++ ){
        item.args[iter] = f.arguments[iter];
      }
    } else {
      item.args = null; // null = argument listing not supported
    }

    ret.push( item );
  }
  return ret;
}

在火狐21和Chromium-25里为我工作过。

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

只需控制台日志错误堆栈。这样你就可以知道你是如何被召唤的

Const hello = () => { console.log(新的错误('I was called').stack) } Const sello = () => { 你好() } 你可以()

只是想让你知道,在PhoneGap/Android上,这个名字似乎不工作。但是arguments.callee.caller.toString()可以做到这一点。

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

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

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