2

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.

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Note that caller is a non-standard property. Your mileage may vary across browsers.
Non standard property indeed but is there something similar in IE? It should only work in IE for my client, Firefox is not supported.
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.
I've edited my response to cover the non-standard contention and added more info on getting the caller of an anonymous function.
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: pastie.org/597543
0

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

2 Comments

than how to get the name of the caller ?
@Umair arguments.callee.caller.name

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.