0

Let's say I have an obj:

var app = {}

and a method inside the object

app = {
   init: function () {
   }
}

how would I go about obtaining the method name 'init' inside of init() without specifically looking for 'init'. This would be in the case that the method name could be anything and I can't rely on searching for a specific name.

app = {
   init: function () {
      //get 'init' method name here
   }
}
app.init();

I tried using callee but that brings back an empty string

1 Answer 1

3

You could use a named function expression:

app = {
  init: function init() {
    console.log(arguments.callee.name);
  }
};

app.init();  // => "init"

Note that use of arguments.callee is forbidden in strict mode.

What you are doing in your example is assigning an anonymous function expression to the property named init on your object. The function itself does not have a name unless you use a named function expression.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, something so simple, didn't even think about declaring its name. That worked perfectly
I had used arguments.callee.name before, but for the life of me could not figure out why it was coming back as an empty string. Not declaring it was staring me right in the face. Ugh, need to step away for a little bit. Thanks again for your answer!
just to be clear, that's actually a named function expression, not a function declaration.

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.