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 1:
For logging/debugging purposes, you can create a new Error
object in the logger and inspect its .stack
property, e.g.
functionlogIt(message) {
var stack = newError().stack,
caller = stack.split('\n')[2].trim();
console.log(caller + ":" + message);
}
functiona(b) {
b()
}
a(functionxyz() {
logIt('hello');
});
Solution 2:
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)();
Solution 3:
After little research here is a good solution :
functiongetFnName(fn) {
var f = typeof fn == 'function';
var s = f && ((fn.name && ['', fn.name]) || fn.toString().match(/function ([^\(]+)/));
return (!f && 'not a function') || (s && s[1] || 'anonymous');
}
functiontest(){
console.log(getFnName(this));
}
test = test.bind(test);
test(); // 'test'
Solution 4:
Building on @georg solution, this one returns just the function name. Note though that it may fail if called from an anonymous function
functiongetFncName() {
const stackLine = (newError())!.stack!.split('\n')[2].trim()
const fncName = stackLine.match(/at Object.([^ ]+)/)?.[1]
return fncName
}
functionFoo() {
console.log(getFncName()) // prints 'Foo'
}
Solution 5:
A simple solution to dynamically retrieve function names [like magic variables] is the use of scoped variables, and the Function.name property.
{
function foo() {
alert (a.name);
}; let a = foo
}
{
function foo2() {
alert(a.name)
}; let a = foo2
};
foo();//logs foo
foo2();//logs foo2
Note: Nested functions cease to be source elements, and are hence not hoisted. Also, this technique cannot work with anonymous functions.
Post a Comment for "Get Current Function Name In Strict Mode"