3

Possible Duplicate:
How do you find out the caller function in JavaScript?

How can I find out in a javascript function which was the calling (the former in the call stack) function?

I would like to determine if the former called function is a __doPostback in the onbeforeunload event.

Community
  • 1
  • 1
Nyla Pareska
  • 1,377
  • 6
  • 22
  • 37

2 Answers2

15

Each function has a caller property defined.

From https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/caller:

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

The Function.caller property is not part of the ECMA3 standard but it's implemented across all major browsers, including IE and Firefox.

If you're using an anonymous function, you can still access the caller property via the arguments.calee property:

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

Note that this code is accessing the current function, and then referencing the same non-standard caller property on it. This is distinct from using the deprecated arguments.caller property directly, which is not implemented in some modern browsers.

James Wheare
  • 4,650
  • 2
  • 26
  • 22
  • 2
    Note that `caller` is a non-standard property. Your mileage may vary across browsers. – T.J. Crowder Aug 26 '09 at 09:46
  • Non standard property indeed but is there something similar in IE? It should only work in IE for my client, Firefox is not supported. – Nyla Pareska Aug 26 '09 at 12:29
  • 4
    `caller` is not part of the ECMA3 standard but it *is* implemented in all major browsers: IE, Firefox, Safari. It should be safe to use in IE. – James Wheare Aug 26 '09 at 15:08
  • I've edited my response to cover the non-standard contention and added more info on getting the caller of an anonymous function. – James Wheare Aug 26 '09 at 15:22
  • FYI, just tested `caller`. As James says, very well-supported. Present and correct on FF3.5, IE7, Chrome2, Safari4 (all on Windows). Opera9 is the odd one out and is seriously broken: It has the property, but it refers to the _callee_, not the caller! (Scary.) Test page here: http://pastie.org/597543 – T.J. Crowder Aug 28 '09 at 09:38
0

In chromeos on cr-48, arguments.callee.caller gives the whole function body as a string, for both named anonymous caller functions.

CqN
  • 139
  • 1
  • 8