javascript - Get function name from inside itself - Stack Overflow

let's say I have a function:function test1() {}I want to return "test1" from within itse

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?

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.

update: for arguments.callee.name Chrome returns blank, IE9 returns undefined. and it does not work with scoped functions.

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?

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.

update: for arguments.callee.name Chrome returns blank, IE9 returns undefined. and it does not work with scoped functions.

Share Improve this question edited Feb 23, 2012 at 22:59 user194076 asked Feb 23, 2012 at 22:49 user194076user194076 9,03724 gold badges101 silver badges158 bronze badges 3
  • 1 possible dup stackoverflow./questions/2648293/… – ajax333221 Commented Feb 23, 2012 at 22:52
  • possible duplicate of Does javascript function know its name and Get function name in javascript. – Felix Kling Commented Feb 23, 2012 at 22:53
  • Possible duplicate of How to get the function name from within that function? – Dan Dascalescu Commented Jun 12, 2019 at 19:53
Add a ment  | 

1 Answer 1

Reset to default 7
var test2 = {
   foo: function() {
   }
};

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

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

This should work:

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745649017a4638147.html

相关推荐

  • javascript - Get function name from inside itself - Stack Overflow

    let's say I have a function:function test1() {}I want to return "test1" from within itse

    22天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信