2

In javascript, I can use foo.caller to get a reference to the function above foo in the stack trace. However, that doesn't work when a function appears multiple times in the same stack trace, foo.caller just returns foo.

Is there a stable, cross-platform method of getting a full stack trace in Javascript? I do not want to get a printable stack trace; rather, I'm doing stack inspection to see if a certain method is anywhere above me in the stack. Here's my current code:

function inFunction(foo) {
    var caller = inFunction.caller;
    var maxDepth = 20;
    while(caller && --maxDepth > 0) {
        if(caller == foo)
            return true;
        caller = caller.caller;
    }
    return false;
}

Any ideas how to deal with a function existing multiple times in the stack trace?

Ben Dilts
  • 10,535
  • 16
  • 54
  • 85
  • Did you check out http://stackoverflow.com/questions/103598/why-was-the-arguments-callee-caller-property-deprecated-in-javascript/235760#235760 – ken Mar 21 '11 at 21:29
  • For a quick reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller – oneamongu Jan 21 '14 at 17:18

1 Answers1

5

Sorry, but there's not. Once you hit a recursive function in the trace it is impossible to get to the calling function.

I spent several days trying to come up with work-arounds to this while writing an IDE in JavaScript for Sun Microsystems. There are none.