本文介绍了javascript - arguments.callee.toString()和arguments.callee.name不返回函数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获取当前正在运行的函数的名称。从我读过的,这应该是可能的使用:

 (arguments.callee.toString())。match(/ function \s +(\ [^ \s\(] +)/)

然而, ,当我在Firefox和Safari(Mac上的最新版本)中运行此命令时,不会返回名称。



console.log(arguments.callee)返回函数的源代码,而不是指定的名称arguments.callee.name返回一个空字符串。

我的示例代码如下所示:

  var testobj = {
testfunc:function(){
console.log((arguments.callee.toString())。match(/ function \\ s +(\ [^ \ s\(] +)/));
}
}
testobj.testfunc();


解决方案

典型的参数.Callee hacks在这里不起作用,因为你所做的事情被分配了一个匿名函数作为对象'testfunc'键的值,在这种情况下,黑客攻击甚至会得到更糟的是,但可以这样做,如下所示:

  var testobj = {
testfunc:function(){
for(var attr in testobj){
if(testobj [attr] == arguments.callee.toString()){
alert(attr);
休息;
}
}
}
}
testobj.testfunc();


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(/function\s+(\[^\s\(]+)/)

However, when I run this in Firefox and Safari (latest versions on Mac) the name is not returned.

console.log( arguments.callee ) returns the source of the function, but not the assigned name. arguments.callee.name returns an empty string.

My sample code is as follows:

var testobj = {
    testfunc: function(){
        console.log( (arguments.callee.toString()).match(/function\s+(\[^\s\(]+)/) );
    }
}
testobj.testfunc();
解决方案

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();

这篇关于javascript - arguments.callee.toString()和arguments.callee.name不返回函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 02:10