最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Get function name from inside itself - Stack Overflow

matteradmin5PV0评论

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"
   }
};
Post a comment

comment list (0)

  1. No comments so far