简体   繁体   中英

Function to get function name inside function?

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?

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"

.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM