1

To get a function's name inside a function I can use this code:

function getmyname() {
    var myName = arguments.callee.toString();
    myName = myName.substr('function '.length);
    myName = myName.substr(0, myName.indexOf('('));
    alert(myName); // getmyname
}

however I need to run this a lot of times, so I'd rather use a function that does it, so it would look like:

function getmyname() {
    alert(getfname()); // getmyname
}

so getfname() would get the name. How can this be done?

lisovaccaro
  • 32,502
  • 98
  • 258
  • 410

2 Answers2

1

You may pass local arguments to getmyname function and use callee.name instead of parsing:

function getmyname(args) {
    return args.callee.name;
}

function getname() {
    alert(getmyname(arguments));
}

getname();  // "getname"
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • And it's worth pointing out that, since the parsing in the OP's code is not needed, there's really no need to have a separate `getmyname` function - just use `alert(args.callee.name)` – Stuart Dec 07 '12 at 01:01
  • @Stuart Yes, `alert(arguments.callee.name)` to be precise. However, I just follow the OP's question. – VisioN Dec 07 '12 at 01:04
  • Thank you for the clarification, I didn't know you could just use that. The answer is right though. – lisovaccaro Dec 07 '12 at 01:49
0

.name is a property which function objects own.

function getmyname() {
    return arguments.callee.name;
}

function getname() {
    alert(getmyname());
}

getname(); // alerts "getmyname"

A word of caution:

arguments.callee alongside other properties, is obsolete in ECMAscript5 strict mode and will throw an error when accessed. So we would need to return getmyname.name, which is obviously not really elegant because we could directly return that string

jAndy
  • 231,737
  • 57
  • 305
  • 359