Search code examples
javascriptstrict

Get current function name in strict mode


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"?


Solution

  • 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');
    });