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.

3

1 Answer 1

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"
   }
};
Sign up to request clarification or add additional context in comments.

3 Comments

It's worth noting arguments.callee and arguments.caller are being deprecated.
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.)
Fails in IE 8 and lower, here's a good examination of named function expressions and why they aren't a good idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.