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"
?
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.
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.
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.
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.
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');
});
You can bind function as its context then you can access its name via this.name
property:
function x(){
console.log(this.name);
}
x.bind(x)();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With