从内部获取函数名称

时间:2023-01-11 01:43:35

let's say I have a function:

假设我有一个功能:

 function test1() {

       }

I want to return "test1" from within itself. I found out that you can do arguments.callee which is going to return the whole function and then do some ugly regex. Any better way?

我想从内部返回“test1”。我发现你可以做arguments.callee,这将返回整个函数,然后做一些丑陋的正则表达式。有更好的方法吗?

what about namespaced functions?

命名空间函数怎么样?

is it possible to get their name as well: e.g.:

是否有可能得到他们的名字:例如:

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. and it does not work with scoped functions.

更新:对于arguments.callee.name Chrome返回空白,IE9返回undefined。它不适用于范围函数。

1 个解决方案

#1


8  

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

You aren't giving the function a name. You are assigning the foo property of test2 to an anonymous function.

您没有给该函数命名。您正在将test2的foo属性分配给匿名函数。

arguments.callee.name only works when functions are declared using the function foo(){} syntax.

arguments.callee.name仅在使用函数foo(){}语法声明函数时有效。

This should work:

这应该工作:

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

#1


8  

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

You aren't giving the function a name. You are assigning the foo property of test2 to an anonymous function.

您没有给该函数命名。您正在将test2的foo属性分配给匿名函数。

arguments.callee.name only works when functions are declared using the function foo(){} syntax.

arguments.callee.name仅在使用函数foo(){}语法声明函数时有效。

This should work:

这应该工作:

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