[javascript] How do you find out the caller function in JavaScript?

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.

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