从函数本身获取函数名称 [英] Get function name from function itself

查看:113
本文介绍了从函数本身获取函数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我可以在javascript中获取当前正在运行的函数的名称吗?

我想从函数本身获取函数名。

I want to get the function name from function itself.

Javascript:

Javascript:

Cube : {
    profile : {
        edit : function(){
            // Get function Path Cube.edit Here
            alert(arguments.callee.name); // Not Working
        }
    }
}


推荐答案

您的代码段中的函数没有名称,它是匿名的。它在配置文件上分配的属性有一个名称( edit ),但该功能没有。不,没有办法获得编辑 profile.edit Cube.profile。从函数对象中编辑

The function in your code snippet has no name, it's anonymous. The property it's assigned to on profile has a name (edit), but the function does not. No, there is no way to get edit or profile.edit or Cube.profile.edit from the function object.

您可以为函数命名:

Cube : {

   profile: {
       edit : function edit(){

         alert(arguments.callee.name);

       }
   }
}

.. 。那是使用命名的函数表达式,它将创建 IE8及更早版本的两个独立的功能对象

...but that's using a named function expression which will create two separate function objects on IE8 and earlier.

你也可以这样做:

Cube : {

   profile: {
       edit : Cube_profile_edit
    }
}
// ...

function Cube_profile_edit(){

    alert(arguments.callee.name);
}

然而,在上述所有问题中,有两个问题:

However, in all of the above, two problems:


  1. 你正在使用 arguments.callee 这在很多浏览器上都非常慢,在严格模式中无效。

  1. You're using arguments.callee which is both very slow on a lot of browsers, and not valid in strict mode.

函数对象的 name 属性是非标准的,这就是为什么这个答案谈到可能需要解析<的结果code>功能#的toString 。问题是,功能#toString 非标准(但相当广泛支持,移动浏览器除外)。

The name property of function objects is non-standard, which is why this answer talks about possibly having to parse the result of Function#toString. The problem is, Function#toString is also non-standard (but fairly broadly supported, except on mobile browsers).

您可以通过搜索属性的 Cube 对象图来避免第二个问题引用该函数,但仍然需要使用 arguments.callee (除非你给函数一个真实的名字,然后在搜索时使用该真实姓名来查找属性路径导致它)。

You could avoid that second problem by searching through the Cube object graph for the property that refers to the function, but that would still require using arguments.callee (unless you give the function a real name and then use that real name when searching to find the property path that leads to it).

这篇关于从函数本身获取函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆