简体   繁体   中英

Get the name of the anonymous variable that contains the function

I have the functions

function getCallingFunctionName() {
    alert(arguments.callee.caller.name.toString();
}

var bob = function() {
    ...
    getCallingFunctionName();
}

When the code is run the value alerted is an empty string is returned. I need to return

 bob

I CANNOT change the original functions (im dealing with a large project with thousands of functions etc.

var bob = function bob() {
    ...
    getCallingFunctionName();
}

Any one got any other ideas ? Its not critical to have but basically to help with debugging.

What if you try to do something like this:

function getCallingFunctionName() {
    try {
        throw new Error();
    }
    catch(e) {
        console.log(e);
    }
}

var bob = function() {
    getCallingFunctionName();
}

It will give you something like this:

Error
    at getCallingFunctionName (<anonymous>:4:15)
    at bob (<anonymous>:12:5)
    at <anonymous>:2:1
    at Object.InjectedScript._evaluateOn (<anonymous>:581:39)
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:540:52)
    at Object.InjectedScript.evaluate (<anonymous>:459:21) 

which you can use for your purpose, ie to extract function name. The only sad thing is that IE supports Error.stack starting from version 10.

Here is a way, that requires a little extra effort/code, but maybe it suits you:

var cache = {};

var bob = function () {
    getCallingFunctionName();
}

function getCallingFunctionName() {
    alert(cache[arguments.callee.caller.toString()]);
}

cache[bob.toString()] = "bob";

bob(); //bob

So you are basically caching the function string representation (which is the complete function body) and using it as a key for the actual function name. Afterwards you can access the name, using again only func.toString() . Of course, this requires that you don't have two functions who have the exact same body.

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