How do you find out the caller function in JavaScript?

前端 未结 30 1566
粉色の甜心
粉色の甜心 2020-11-21 17:46
function main()
{
   Hello();
}

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

Is there a way to find out the call

相关标签:
30条回答
  • 2020-11-21 18:09

    I know you mentioned "in Javascript", but if the purpose is debugging, I think it's easier to just use your browser's developer tools. This is how it looks in Chrome: enter image description here Just drop the debugger where you want to investigate the stack.

    0 讨论(0)
  • 2020-11-21 18:09

    I would do this:

    function Hello() {
      console.trace();
    }
    
    0 讨论(0)
  • 2020-11-21 18:13

    I wanted to add my fiddle here for this:

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

    I tested this is chrome, safari and IE (10 and 8). Works fine. There is only 1 function that matters, so if you get scared by the big fiddle, read below.

    Note: There is a fair amount of my own "boilerplate" in this fiddle. You can remove all of that and use split's if you like. It's just an ultra-safe" set of functions I've come to rely on.

    There is also a "JSFiddle" template in there that I use for many fiddles to simply quick fiddling.

    0 讨论(0)
  • 2020-11-21 18:15

    2018 Update

    caller is forbidden in strict mode. Here is an alternative using the (non-standard) Error stack.

    The following function seems to do the job in Firefox 52 and Chrome 61-71 though its implementation makes a lot of assumptions about the logging format of the two browsers and should be used with caution, given that it throws an exception and possibly executes two regex matchings before being done.

    'use strict';
    const fnNameMatcher = /([^(]+)@|at ([^(]+) \(/;
    
    function fnName(str) {
      const regexResult = fnNameMatcher.exec(str);
      return regexResult[1] || regexResult[2];
    }
    
    function log(...messages) {
      const logLines = (new Error().stack).split('\n');
      const callerName = fnName(logLines[1]);
    
      if (callerName !== null) {
        if (callerName !== 'log') {
          console.log(callerName, 'called log with:', ...messages);
        } else {
          console.log(fnName(logLines[2]), 'called log with:', ...messages);
        }
      } else {
        console.log(...messages);
      }
    }
    
    function foo() {
      log('hi', 'there');
    }
    
    (function main() {
      foo();
    }());

    0 讨论(0)
  • 2020-11-21 18:16

    StackTrace

    You can find the entire stack trace using browser specific code. The good thing is someone already made it; here is the project code on GitHub.

    But not all the news is good:

    1. It is really slow to get the stack trace so be careful (read this for more).

    2. You will need to define function names for the stack trace to be legible. Because if you have code like this:

      var Klass = function kls() {
         this.Hello = function() { alert(printStackTrace().join('\n\n')); };
      }
      new Klass().Hello();
      

      Google Chrome will alert ... kls.Hello ( ... but most browsers will expect a function name just after the keyword function and will treat it as an anonymous function. An not even Chrome will be able to use the Klass name if you don't give the name kls to the function.

      And by the way, you can pass to the function printStackTrace the option {guess: true} but I didn't find any real improvement by doing that.

    3. Not all browsers give you the same information. That is, parameters, code column, etc.


    Caller Function Name

    By the way, if you only want the name of the caller function (in most browsers, but not IE) you can use:

    arguments.callee.caller.name
    

    But note that this name will be the one after the function keyword. I found no way (even on Google Chrome) to get more than that without getting the code of the whole function.


    Caller Function Code

    And summarizing the rest of the best answers (by Pablo Cabrera, nourdine, and Greg Hewgill). The only cross-browser and really safe thing you can use is:

    arguments.callee.caller.toString();
    

    Which will show the code of the caller function. Sadly, that is not enough for me, and that is why I give you tips for the StackTrace and the caller function Name (although they are not cross-browser).

    0 讨论(0)
  • 2020-11-21 18:16

    Try accessing this:

    arguments.callee.caller.name
    
    0 讨论(0)
提交回复
热议问题