The problem
I need to fetch the name of an anonymous function defined as an expression when it is called.
What I've tried so far
In the following example, I am able to console.log
the name of the function like this:
function init() {
console.log(init.name); // Outputs "init".
}
The console.log
will output init
respectively. When I define the function as an expression, console.log(init.name);
will no longer output init
, because technically I'm asking for the name of an anonymous function (as proven by console.log(init);
in the second example).
var init = function() {
console.log(init.name); // Outputs nothing.
};
The following example will initially solve the problem, as suggested by robertklep:
var init = function init() {
console.log(init.name); // Outputs "init".
};
This way, I give the anonymous function a name and I can just fetch the name with init.name
. Although, this is not the solution I'm looking for.
The question
Is it possible to obtain the name of an anonymous function defined as an expression when it is called at all? Am I forced to give the function a name too if I want to achieve this?