从函数本身获取函数名称

编程入门 行业动态 更新时间:2024-10-28 12:24:05
本文介绍了从函数本身获取函数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: 我可以在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:

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

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

    函数对象的 name 属性是非标准的,这就是为什么这个答案谈到可能需要解析功能#的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).

  • 更多推荐

    从函数本身获取函数名称

    本文发布于:2023-11-28 09:19:34,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1641819.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:函数   名称

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!