I\'m trying to get the name of the currently running function. From what I\'ve read, this should be possible using:
(arguments.callee.toString()).match(/func
I found that if you simply log the function object, like so:
console.log(arguments.callee)
or
console.debug(arguments.callee)
that you simply get the function name in the console log with some options.
The typical arguments.callee hacks don't work here because what you've done is assigned an anonymous function as the value for the object's 'testfunc' key. In this case the hacking even gets worse, but it can be done, as follows:
var testobj = {
testfunc: function(){
for (var attr in testobj) {
if (testobj[attr] == arguments.callee.toString()) {
alert(attr);
break;
}
}
}
}
testobj.testfunc();
You declared an anonymous function with
function(){
You should declare it as
function testfunc(){
to get the name printed.
On firefox 3.5, Safari 5, and Chrome 6.0 you can use:
function myFunctionName() {
alert("Name is " + arguments.callee.name );
}
myFunctionName();
You can also get the function that called the current one using arguments.callee.caller.
/function\s+(\[^\s\(]+)/
What's with the backslash before [
? I don't think you want a literal square bracket here. Without that it should work.
Although I'd strongly recommend against anything to do with sniffing function name or especially sniffing caller function. Almost anything you might do using these hideous hacks will be better done using some combination of closures and lookups.
First of all, the function doesn't have a name. The function name is what you put in-between function
and the arguments list (...)
. Here's how to get a function's name (don't use the name
property, as it can be changed):
var fName = arguments.callee.toString(0).match(
/^function\s*(?:\s+([\w\$]*))?\s*\(/
);
fName = (fName ? fName[1] : "");