How do you find out the caller function in JavaScript?

前端 未结 30 1499
粉色の甜心
粉色の甜心 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 17:49

    As far as I know, we have 2 way for this from given sources like this-

    1. arguments.caller

      function whoCalled()
      {
          if (arguments.caller == null)
             console.log('I was called from the global scope.');
          else
             console.log(arguments.caller + ' called me!');
      }
      
    2. Function.caller

      function myFunc()
      {
         if (myFunc.caller == null) {
            return 'The function was called from the top!';
         }
         else
         {
            return 'This function\'s caller was ' + myFunc.caller;
          }
      }
      

    Think u have your answer :).

    0 讨论(0)
  • 2020-11-21 17:53

    Here, everything but the functionname is stripped from caller.toString(), with RegExp.

    <!DOCTYPE html>
    <meta charset="UTF-8">
    <title>Show the callers name</title><!-- This validates as html5! -->
    <script>
    main();
    function main() { Hello(); }
    function Hello(){
      var name = Hello.caller.toString().replace(/\s\([^#]+$|^[^\s]+\s/g,'');
      name = name.replace(/\s/g,'');
      if ( typeof window[name] !== 'function' )
        alert ("sorry, the type of "+name+" is "+ typeof window[name]);
      else
        alert ("The name of the "+typeof window[name]+" that called is "+name);
    }
    </script>
    
    0 讨论(0)
  • 2020-11-21 17:53

    here is a function to get full stacktrace:

    function stacktrace() {
    var f = stacktrace;
    var stack = 'Stack trace:';
    while (f) {
      stack += '\n' + f.name;
      f = f.caller;
    }
    return stack;
    }
    
    0 讨论(0)
  • 2020-11-21 17:54

    If you are not going to run it in IE < 11 then console.trace() would suit.

    function main() {
        Hello();
    }
    
    function Hello() {
        console.trace()
    }
    
    main()
    // Hello @ VM261:9
    // main @ VM261:4
    
    0 讨论(0)
  • 2020-11-21 17:54

    Note you can't use Function.caller in Node.js, use caller-id package instead. For example:

    var callerId = require('caller-id');
    
    function foo() {
        bar();
    }
    function bar() {
        var caller = callerId.getData();
        /*
        caller = {
            typeName: 'Object',
            functionName: 'foo',
            filePath: '/path/of/this/file.js',
            lineNumber: 5,
            topLevelFlag: true,
            nativeFlag: false,
            evalFlag: false
        }
        */
    }
    
    0 讨论(0)
  • 2020-11-21 17:55
    function Hello() {
        alert(Hello.caller);
    }
    
    0 讨论(0)
提交回复
热议问题