Question

How is it possible to learn the name of function I am in?

The below code alerts 'Object'. But I need to know how to alert "Outer."

function Outer(){

    alert(typeof this);

}
Was it helpful?

Solution

I think that you can do that :

var name = arguments.callee.toString();

For more information on this, take a look at this article.

function callTaker(a,b,c,d,e){
  // arguments properties
  console.log(arguments);
  console.log(arguments.length);
  console.log(arguments.callee);
  console.log(arguments[1]);
  // Function properties
 console.log(callTaker.length);
  console.log(callTaker.caller);
  console.log(arguments.callee.caller);
  console.log(arguments.callee.caller.caller);
  console.log(callTaker.name);
  console.log(callTaker.constructor);
}

function callMaker(){
  callTaker("foo","bar",this,document);
}

function init(){
  callMaker();
}

OTHER TIPS

This will work:

function test() {
  var z = arguments.callee.name;
  console.log(z);
}

As of ES6, you can use Function.prototype.name. This has the added benefit of working with arrow functions, since they do not have their own arguments object.

function logFuncName() {
  console.log(logFuncName.name);
}

const logFuncName2 = () => {
  console.log(logFuncName2.name);
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top