SunnyShah
SunnyShah

Reputation: 30467

Getting caller name in JS function

Please help me with below problem.

var test = new Object();
test.testInner = new Object();

test.testInner.main = function ()
{
   Hello();
}

function Hello()
{
  /**** Question: currently I am getting blank string with below code,
   **** Is there any way to get function name as "test.testInner.main" over here? */
  console.log(arguments.callee.caller.name);
}
test.testInner.main();

Upvotes: 0

Views: 898

Answers (2)

Anoop
Anoop

Reputation: 23208

test.testInner.main has reference of anonymous (without name) function. You can get name by assigning name to them. modified code:

var test = new Object();
test.testInner = new Object();

test.testInner.main = function main()
{
   Hello();
}

function Hello()
{
  /**** Question: currently I am getting blank string with below code,
   **** Is there any way to get function name as "test.testInner.main" over here? */
  console.log(arguments.callee.caller.name);
}
test.testInner.main();

jsfiddle

Upvotes: 1

You can set the context of a function in Javascript.

function hello() { 
    console.log(this);
}
some.other.object = function() {
    hello.call(this, arguments, to, hello);
}

this will be some.other.object in hello().

In your example, the caller is main, and it doesn't have a name property because it is anonymous. Like here: Why is arguments.callee.caller.name undefined?

Besides, arguments is deprecated and should thus not be used.

Upvotes: 0

Related Questions