views:

321

answers:

1

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.

+6  A: 

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
Note that `caller` is a non-standard property. Your mileage may vary across browsers.
T.J. Crowder
Will that also work in IE?
Nyla Pareska
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
`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
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
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