代码之家  ›  专栏  ›  技术社区  ›  Geuis

javascript-arguments.callee.toString()和arguments.callee.name不返回函数名

  •  8
  • Geuis  · 技术社区  · 15 年前

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

    但是,当我在Firefox和Safari(Mac上的最新版本)中运行此功能时,不会返回名称。

    我的示例代码如下:

    var testobj = {
        testfunc: function(){
            console.log( (arguments.callee.toString()).match(/function\s+(\[^\s\(]+)/) );
        }
    }
    testobj.testfunc();
    
    8 回复  |  直到 15 年前
        1
  •  8
  •   Dexygen    13 年前

    典型的arguments.callee hack在这里不起作用,因为您所做的是为对象的“testfunc”键分配一个匿名函数作为值。在这种情况下,黑客行为甚至会变得更糟,但可以这样做,如下所示:

    var testobj = {
        testfunc: function(){
          for (var attr in testobj) {
                  if (testobj[attr] == arguments.callee.toString()) {
                      alert(attr);
                      break;
                    }
                }
        }
    }
    testobj.testfunc();
    
        2
  •  10
  •   Eric Bréchemier    15 年前

    您使用声明了一个匿名函数

    function(){
    

    你应该申报为

    function testfunc(){
    

        3
  •  3
  •   Ben Clayton    14 年前

    在firefox 3.5、Safari 5和Chrome 6.0上,您可以使用:

    function myFunctionName() {
     alert("Name is " + arguments.callee.name );
    }
    
    myFunctionName();
    

    您还可以使用arguments.callee.caller获取调用当前函数的函数。

        4
  •  2
  •   bobince    15 年前
    /function\s+(\[^\s\(]+)/
    

    以前的反斜杠是怎么回事 [

    虽然我会 强烈地

        5
  •  2
  •   Murray Todd Williams    13 年前

    关键字,我们可以通过 A.callee for(本文件中的var o)

    returnMyName = function() {
      for (var o in this) {
        if (arguments.callee===this[o]) return o;
      }
    };
    

    这应该是健壮的,并避免任何奇怪的IE浏览器行为访问命名函数等。

        6
  •  2
  •   yckart Matthew Crumley    11 年前
    Function.prototype.getName = function(fn) {
        if(Function.name || Function.prototype.name) return this.name;
        return this.toString().match(/^function\s+(\w+)\s*\(/)[1];
    };
    
        7
  •  0
  •   Eli Grey    15 年前

    首先,函数没有名称。函数名是介于两者之间的名称 function 和参数列表 (...) name 属性,因为它可以更改):

    var fName = arguments.callee.toString(0).match(
      /^function\s*(?:\s+([\w\$]*))?\s*\(/
    );
    fName = (fName ? fName[1] : "");
    
        8
  •  0
  •   Dave Van den Eynde    14 年前

    console.log(arguments.callee)
    

    console.debug(arguments.callee)