5

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.

user194076
  • 8,787
  • 23
  • 94
  • 154
  • 1
    possible dup http://stackoverflow.com/questions/2648293/javascript-get-function-name – ajax333221 Feb 23 '12 at 22:52
  • possible duplicate of [Does javascript function know its name](http://stackoverflow.com/questions/5599513/does-javascript-function-know-its-name) and [Get function name in javascript](http://stackoverflow.com/q/3178892/218196). – Felix Kling Feb 23 '12 at 22:53
  • Possible duplicate of [How to get the function name from within that function?](https://stackoverflow.com/questions/2648293/how-to-get-the-function-name-from-within-that-function) – Dan Dascalescu Jun 12 '19 at 19:53

1 Answers1

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"
   }
};
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • 5
    It's worth noting `arguments.callee` and `arguments.caller` are being deprecated. – T. Stone Feb 23 '12 at 23:09
  • 1
    And note that when the function runs it doesn't know that it "belongs" to `test2`. (Because it doesn't "belong", it is just that `test2` happens to have a property `foo` that references the function; you could create other references to the same function. Depending on how you call it it _may_ have a `this` reference to that object.) – nnnnnn Feb 24 '12 at 00:11
  • 1
    Fails in IE 8 and lower, here's a good examination of [named function expressions](http://kangax.github.com/nfe/) and why they aren't a good idea. – RobG Feb 24 '12 at 00:31