简体   繁体   中英

Getting the name of a variable function expression?

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?

You can't, because coded like that, it's an anonymous function (in other words: it doesn't have a name).

But you can give it a name if you like:

var init = function theFunctionName() {
  console.log(init.name); // outputs: theFunctionName
};

Anonymous function without having any name will give black string if you try .name .

var init = function() {
  console.log(typeof init.name);// will give blank string 
};

But if you give name to function it will give you name.

您可以这样尝试:

console.log(init.toString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM