allnodcoms
allnodcoms

Reputation: 1262

Using `function.caller`

Two part question:

  1. How to get function.caller from an object method.
  2. How to use that value to actually call the function.

Example:

foo = {
    bar: function() {console.log(bar.caller);}
}

>> SyntaxError: function statement requires a name

Example 2:

[bar.caller](); ?

Thanks in advance

Upvotes: 1

Views: 163

Answers (2)

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

To get the caller (if it exist) use this:

var caller = arguments.callee.caller;

To use it you have to check if it exist first like this:

if(caller)
    caller();

EXAMPLE:

function foo(param){
  if(param == 5) return console.log(param);
  
  var caller = arguments.callee.caller;
  if(caller)
    caller(param + 1);
}

function bar(param){
  foo(param);
}

foo(3); // won't log anything (no caller and param != 5)

bar(3); // will cause a recursion until param == 5 then logs it.

Upvotes: 0

Pointy
Pointy

Reputation: 413727

The problem with the code you posted is that bar doesn't mean anything inside that anonymous function. The name "bar" is a property name of the object assigned to foo. Thus this works fine:

var foo = {
  bar: function() {
    console.log("Caller is: " + foo.bar.caller);
  }
};

function x() {
  foo.bar();
}

x();

The function doesn't need a name; that's irrelevant. In order to get to the caller property you need a reference to the function, and that can come from anywhere. This would therefore also work:

var foo = {
  bar: function() {
    console.log("Caller is: " + this.bar.caller);
  }
};

function x() {
  foo.bar();
}

x();

because when that function is invoked as foo.bar() the value of this will be the "foo" object.

Upvotes: 1

Related Questions