Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current function name in strict mode

Tags:

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

like image 313
exebook Avatar asked Jul 18 '16 11:07

exebook


People also ask

How do you print a function name in Python?

Method 1: Get Function Name in Python using function. func_name. By using a simple function property function, func_name, one can get the name of the function and hence can be quite handy for the Testing purpose and also for documentation at times. The drawback is that this works just for Python2.

What is correct way to run a JavaScript in strict mode?

Strict mode for functions Likewise, to invoke strict mode for a function, put the exact statement "use strict"; (or 'use strict'; ) in the function's body before any other statements. The "use strict" directive can only be applied to the body of functions with simple parameters.

What is strictMode in JavaScript?

Strict mode changes previously accepted "bad syntax" into real errors. As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.

Why this is undefined in strict mode?

This proves that this here refers to the global object, which is the window object in our case. Note that, if strict mode is enabled for any function then the value of this will be undefined because in strict mode global object refers to undefined in place of the window object.


2 Answers

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');
});
like image 164
georg Avatar answered Sep 18 '22 00:09

georg


You can bind function as its context then you can access its name via this.nameproperty:

function x(){
  console.log(this.name);
}
x.bind(x)();
like image 23
LJ Wadowski Avatar answered Sep 20 '22 00:09

LJ Wadowski