caller

Non-standard

Summary

Returns the function that invoked the specified function.

This property is not part of ECMA-262 Edition 3 standard. It is implemented at least in SpiderMonkey (the JavaScript engine used in Mozilla) (see bug 65683 ), V8 (the JavaScript engine used in Chrome) and JScript.

Property of Function
Implemented in JavaScript 1.5
ECMAScript Edition none

Description

If the function f was invoked by the top level code, the value of f.caller is null, otherwise it's the function that called f

This property replaces deprecated arguments.caller.

Notes

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

function f(n) { g(n-1) }
function g(n) { if(n>0) f(n); else stop() }
f(2)

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.

The special property __caller__, which returned the activation object of the caller thus allowing to reconstruct the stack, was removed for security reasons.

Examples

Example: Checking the value of a function's caller property

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

 

Browser Support

Function.caller is currently supported by all major browsers: Firefox, Safari, Chrome, Opera and IE.  Test page with results.

 

Tags (2)

Edit tags

Attachments (0)

 

Attach file