Reputation: 3238
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.
Upvotes: 3
Views: 250
Reputation: 10536
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.
Upvotes: 0
Reputation: 193301
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, i.e. to extract function name. The only sad thing is that IE supports Error.stack starting from version 10.
Upvotes: 2