h bob
h bob

Reputation: 3780

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?

Upvotes: 2

Views: 102

Answers (2)

Dan Prince
Dan Prince

Reputation: 29989

You aren't overwriting anything.

The only way the .name property can be set is if you declare the function with a name.

function nameHere() {

}

If the function is named, then the name property will use that 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.

Upvotes: 2

Alberto Zaccagni
Alberto Zaccagni

Reputation: 31560

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).

About shadowing: Variable shadowing in JavaScript

Upvotes: 3

Related Questions