views:

145

answers:

2

Hi,

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);

}
+4  A: 

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();
}
marcgg
unfortunately `arguments.callee` is deprecated, but since ECMA hasn't defined any substitute yet, this is the way to go.
Boldewyn
@boldewyn: after more searching I saw that too. But while it's deprecated it still works in most browsers. And like you said, there's no alternative sooooo... ^^
marcgg
@Boldewyn, `arguments.callee` is not just deprecated. When strict mode is enabled, accessing it would cause TypeError.
bryantsai
I'm not sure arguments.callee is deprecated.Function.arguments and Function.arguments.callee are, but not the callee property of the arguments of a function. From MDC:- JavaScript 1.4: Deprecated callee as a property of Function.arguments, retained it as a property of a function's local arguments variable.
meouw
+1  A: 

This will work:

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