Javascript - Arguments.callee.toString() And Arguments.callee.name Does Not Return Function Name
Solution 1:
You declared an anonymous function with
function(){
You should declare it as
function testfunc(){
to get the name printed.
Solution 2:
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();
Solution 3:
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.
Solution 4:
/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.
Solution 5:
I think there's a much cleaner and elegant solution to all this. Assuming the function is a member of some higher-level object—and that's always going to be the case, even if the function's owner is "window" or some other global object, we can access the global object via the this keyword, we can access the function itself via arguments.callee and we can access all the parent's object (function) names via for (var o in this), so you should be able to get the desired information fairly easily as...
returnMyName = function() {
for (var o in this) {
if (arguments.callee===this[o]) return o;
}
};
That should be robust and avoid any weird IE browser behaviors accessing named functions, etc.
Post a Comment for "Javascript - Arguments.callee.toString() And Arguments.callee.name Does Not Return Function Name"