Get current function name in strict mode

exebook picture exebook · Jul 18, 2016 · Viewed 8.9k times · Source

I need the current function name as a string to log to our log facility. But arguments.callee.name only works in loose mode. How to get the function name under "use strict"?

Answer

georg picture georg · Jul 18, 2016

For logging/debugging purposes, you can create a new Error object in the logger and inspect its .stack property, e.g.

function logIt(message) {
    var stack = new Error().stack,
        caller = stack.split('\n')[2].trim();
    console.log(caller + ":" + message);
}

function a(b) {
    b()
}

a(function xyz() {
    logIt('hello');
});