[英]Anonymous function's name
I want to get the name of an anonymous function . 我想获得一个匿名函数的名称 。
The typical answer is 典型的答案是
var aName = function a(){};
Which gives this 这给这个
aName.name === "a" // true
But I found that this works too: 但是我发现这也可行:
var a = function a(){};
Which gives this 这给这个
a.name === "a" // true
typeof a === "function" // true
However, I feel like I'm asking for trouble there, as I'm overwriting names. 但是,我觉得我在要求麻烦,因为我要覆盖名称。 Are there any repercussions for using such a syntax?
使用这种语法有什么影响吗?
The two approaches are almost identical, the only difference is that in the second you are shadowing a
as the variable identifier with a
as the function identifier (when a
is used inside the a
function). 这两种方法几乎相同,唯一的区别是,在第二您阴影
a
与可变标识符a
作为函数标识符(当a
设置在内部使用a
功能)。
About shadowing: Variable shadowing in JavaScript 关于阴影: JavaScript中的可变阴影
You aren't overwriting anything. 您不会覆盖任何内容。
The only way the .name
property can be set is if you declare the function with a name. 设置
.name
属性的唯一方法是使用名称声明函数。
function nameHere() {
}
If the function is named, then the name property will use that name. 如果函数被命名,则name属性将使用该名称。
If the function isn't named, then it is anonymous. 如果该函数未命名,则它是匿名的。
var nameHere = function() {
};
There is no (proper) way to get the name of the variable that an anonymous function is assigned to. 没有(正确)方法来获取分配了匿名函数的变量的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.