javascript - 通过匿名函数获取变量名

标签 javascript function anonymous-function

是否可以找到匿名函数的名称?

例如试图找到一种方法来提醒此代码中的 anonyFufindMe http://jsfiddle.net/L5F5N/1/

function namedFu(){
    alert(arguments.callee);
    alert(arguments.callee.name);
    alert(arguments.callee.caller);
    alert(arguments.caller);
    alert(arguments.name);
}

var anonyFu = function() {
    alert(arguments.callee);
    alert(arguments.callee.name);
    alert(arguments.callee.caller);
    alert(arguments.caller);
    alert(arguments.name);
}

var findMe= function(){ 
    namedFu();
    anonyFu();
}
findMe();

这是为了一些内部测试,所以不需要跨浏览器。事实上,即使必须安装插件,我也会很高兴。

最佳答案

您可以通过使用 arguments.callee 以编程方式从函数内部识别函数的任何属性,甚至是未命名的匿名函数。所以你可以用这个简单的技巧来识别函数:

每当你创建一个函数时,给它分配一些你可以在以后用来识别它的属性。

例如,始终创建一个名为 id 的属性:

var fubar = function() {
   this.id = "fubar";
   //the stuff the function normally does, here
   console.log(arguments.callee.id);
}

arguments.callee 是函数本身,因此可以像上面的 id 一样访问该函数的任何属性,甚至是您自己分配的属性。

Callee 已被正式弃用,但在几乎所有浏览器中仍然有效,并且在某些情况下仍然没有替代品。你只是不能在“严格模式”下使用它。

当然,您也可以为匿名函数命名,例如:

var fubar = function foobar() {
   //the stuff the function normally does, here
   console.log(arguments.callee.name);
}

但这显然不够优雅,因为您不能(在本例中)在两个位置都将其命名为 fubar;我必须使用实际名称 foobar。

如果你所有的函数都有描述它们的注释,你甚至可以捕获它,就像这样:

var fubar = function() {
   /* 
      fubar is effed up beyond all recognition 
      this returns some value or other that is described here
    */
   //the stuff the function normally does, here
   console.log(arguments.callee.toString().substr(0, 128);
}

请注意,您还可以使用 argument.callee.caller 来访问调用当前函数的函数。这使您可以从函数外部访问函数的名称(或属性,如 id 或文本中的注释)。

您这样做的原因是您想要找出调用相关函数的内容。这可能是您首先希望以编程方式查找此信息的原因。

因此,如果上面的 fubar() 示例之一调用了以下函数:

var kludge = function() {
   console.log(arguments.callee.caller.id); // return "fubar" with the first version above
   console.log(arguments.callee.caller.name); // return "foobar" in the second version above
   console.log(arguments.callee.caller.toString().substr(0, 128);
     /* that last one would return the first 128 characters in the third example, 
        which would happen to include the name in the comment. 
        Obviously, this is to be used only in a desperate case, 
        as it doesn't give you a concise value you can count on using)
     */
}

关于javascript - 通过匿名函数获取变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13260488/

相关文章:

javascript - typescript -在多维对象中查找匹配的键和路径

javascript - 基于另一个对象递归更新特定键的嵌套对象值

javascript - 使用 AJAX 发送的变量在 PHP 中未定义

c++ - 调用扩展类函数

python - 并排打印两个函数

javascript - 防止独立 Web 应用程序中的链接使用 Rails 上的模式打开 Mobile Safari

python - Z3 发现模型与公理不一致

javascript - 如何删除带有匿名函数的addEventListener 的EventListener?

c# - 如何声明具有匿名返回类型的函数?

addEventListener 匿名函数中的 Javascript 变量范围