简体   繁体   English

从内部获取函数名称

[英]Get function name from inside itself

let's say I have a function: 假设我有一个功能:

 function test1() {

       }

I want to return "test1" from within itself. 我想从内部返回“test1”。 I found out that you can do arguments.callee which is going to return the whole function and then do some ugly regex. 我发现你可以做arguments.callee ,它将返回整个函数,然后做一些丑陋的正则表达式。 Any better way? 有更好的方法吗?

what about namespaced functions? 命名空间函数怎么样?

is it possible to get their name as well: eg: 是否有可能得到他们的名字:例如:

var test2 = 
{
 foo: function() {
    }
};

I want to return foo for this example from within itself. 我想从内部返回foo这个例子。

update: for arguments.callee.name Chrome returns blank, IE9 returns undefined. 更新:对于arguments.callee.name Chrome返回空白,IE9返回undefined。 and it does not work with scoped functions. 它不适用于范围函数。

var test2 = {
   foo: function() {
   }
};

You aren't giving the function a name. 您没有给该函数命名。 You are assigning the foo property of test2 to an anonymous function. 您正在将test2foo属性分配给匿名函数。

arguments.callee.name only works when functions are declared using the function foo(){} syntax. arguments.callee.name仅在使用function foo(){}语法声明函数时才有效。

This should work: 这应该工作:

var test2 = {
   foo: function foo() {
      console.log(arguments.callee.name); // "foo"
   }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM