简体   繁体   English

获取变量函数表达式的名称?

[英]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: 在以下示例中,我可以使用console.log这样的函数名:

function init() {
    console.log(init.name); // Outputs "init".
}

The console.log will output init respectively. console.log将分别输出init When I define the function as an expression, console.log(init.name); 当我将函数定义为表达式时, 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). 将不再输出init ,因为从技术上讲,我正在询问匿名函数的名称(第二个示例已由console.log(init);证明)。

var init = function() {
    console.log(init.name); // Outputs nothing.
};

The following example will initially solve the problem, as suggested by robertklep: 如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 . 这样,我给匿名函数起一个名字,我就可以用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 . 如果您尝试使用.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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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