Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top