简体   繁体   中英

Get function name from inside itself

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: eg:

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.

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"
   }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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