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?

3
  • Read this: Why was the arguments.callee.caller property deprecated in JavaScript? Commented Dec 7, 2012 at 0:52
  • Probably also worth asking yourself if you really need to do that. Commented Dec 7, 2012 at 0:53
  • What would getfname() do with the name? Just return it? If so, why wouldn't you just reference the name in the first place? Commented Dec 7, 2012 at 0:54

2 Answers 2

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"
Sign up to request clarification or add additional context in comments.

3 Comments

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 Yes, alert(arguments.callee.name) to be precise. However, I just follow the OP's question.
Thank you for the clarification, I didn't know you could just use that. The answer is right though.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.