Function Caller

Why Caller?

The function caller () returns the function that calls the specified function.

When the function is called by a top-level code, the function.call is set to null. At the same time, this property changes the arguments object to the outdated arguments.caller property.

Additional information: There is one more function that serves the same function. The caller feature has been removed because it has corrupted the system security.

Note that in case of recursion, you can’t reconstruct the call stack using this property. Consider:

    function f(x) { g(x - 1); }
    function g(x) { if (x > 0) { f(x); } else { stop(); } }
    f(5);

At the moment stop() is called the call stack will be:

f(2) -> g(1) -> f(1) -> g(0) -> stop()

The following is true:

stop.caller === g && f.caller === g && g.caller === f

so if you tried to get the stack trace in the stop() function like this:

var f = stop;
var stack = 'Stack trace:';
while (f) {
  stack += '\n' + f.name;
  f = f.caller;
}

the loop would never stop.


Example

The following code checks the value a function’s caller property.

function myFunc() {
  if (myFunc.caller == null) {
    return 'The function was called from the top!';
  } else {
    return 'This function\'s caller was ' + myFunc.caller;
  }
}

Source of this page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller


Browser Support

Chromeyes
Edgeyes
Firefox1
Internet Explorer8
Operayes
Safariyes
Android webviewyes
Chrome for Androidyes
Edge mobileyes
Firefox for Android4
Opera Androidyes


One thought on “Function Caller

Add yours

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a website or blog at WordPress.com

Up ↑

Design a site like this with WordPress.com
Get started