How do you find out the caller function in JavaScript?

前端 未结 30 1880
粉色の甜心
粉色の甜心 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: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();
    }());

提交回复
热议问题