1

Can I get the name of the function using the variable that is present inside the function?

function abcd() {
    var temp;
    alert(" name of the function using temp ");
};

How do I get the name of the function 'abcd' using temp?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
ashok_khuman
  • 599
  • 2
  • 8
  • 17
  • Why do you have to use the variable? You can get the function name, but not from the variable. – Barmar Jul 15 '14 at 10:07

2 Answers2

2

You can use arguments.callee.name, like this

function abcd() {
    console.log("name of the function using", arguments.callee.name);
};

abcd();
# name of the function using abcd

Note: arguments.callee.name will work only with the functions defined with a name. It will not work with anonymous functions. For example, if you had defined your function, like this

var abcd = function () {
    console.log("name of the function using", arguments.callee.name);
};

abcd() would just print name of the function using. Because arguments.callee.name would be an empty string in this case.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
2

In "non strict" mode you can use arguments.callee.name.

But in general you shouldn't - it's unsafe to assume anything about the variable(s) an object or function is known by from within because there can be more than one, or in the case of an anonymous function no name at all.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • How can a function have more than one name? It can be assigned to multiple variables, but those aren't its name, they're just other ways to refer to it. – Barmar Jul 15 '14 at 10:08
  • @Barmar yes, that's strictly correct, but for _most_ purposes the variables and the formal name assigned to a function are the same thing. But if you've already assigned a formal name to a function why do you need it internally (hence its deprecation in ES5 strict mode) – Alnitak Jul 15 '14 at 10:10