C
Csaba Gabor
Inside a function, I'd like to know the call stack. By this I mean
that I'd like to know the function that called this one, that one's
caller and so on.
So I thought to do:
<script type='text/javascript'>
function myFunc(lev) {
// if (lev) return myFunc(lev-1);
var aStack=[];
nextFunc = arguments.callee;
while (nextFunc) {
aStack.push(nextFunc.name ? nextFunc.name : nextFunc.toString());
nextFunc = nextFunc.caller;
}
return aStack;
}
function foo() { return myFunc(1); }
function bar() { return foo("frob"); }
alert (bar("baz"));
</script>
This works as expected (on FF 1.5+ / IE 6 on my WinXP Pro). However,
if I uncomment the first line of myFunc to make it recursive (making
sure I don't have any unsaved work or other browser windows open), the
function stalls out because arguments.callee.caller==arguments.callee,
so the script goes into an infinite loop.
In other words, myFunc at the lowest level knows it was called by
myFunc (hence I can detect recursion), but I don't see how to determine
how many levels deep myFunc is, nor its original caller. Anyone know
an alternate approach?
Thanks,
Csaba Gabor from Vienna
I did try an approach of getting to the arguments.callee of the caller
(since arguments.callee.caller in [the outer call, ] myFunc(1) is
correct, returning foo), but no dice. I got the same results (of an
infinite loop) after adding the following two lines after nextFunc =
nextFunc.caller;
if (!nextFunc) break;
var nextFunc = nextFunc.arguments.callee;
that I'd like to know the function that called this one, that one's
caller and so on.
So I thought to do:
<script type='text/javascript'>
function myFunc(lev) {
// if (lev) return myFunc(lev-1);
var aStack=[];
nextFunc = arguments.callee;
while (nextFunc) {
aStack.push(nextFunc.name ? nextFunc.name : nextFunc.toString());
nextFunc = nextFunc.caller;
}
return aStack;
}
function foo() { return myFunc(1); }
function bar() { return foo("frob"); }
alert (bar("baz"));
</script>
This works as expected (on FF 1.5+ / IE 6 on my WinXP Pro). However,
if I uncomment the first line of myFunc to make it recursive (making
sure I don't have any unsaved work or other browser windows open), the
function stalls out because arguments.callee.caller==arguments.callee,
so the script goes into an infinite loop.
In other words, myFunc at the lowest level knows it was called by
myFunc (hence I can detect recursion), but I don't see how to determine
how many levels deep myFunc is, nor its original caller. Anyone know
an alternate approach?
Thanks,
Csaba Gabor from Vienna
I did try an approach of getting to the arguments.callee of the caller
(since arguments.callee.caller in [the outer call, ] myFunc(1) is
correct, returning foo), but no dice. I got the same results (of an
infinite loop) after adding the following two lines after nextFunc =
nextFunc.caller;
if (!nextFunc) break;
var nextFunc = nextFunc.arguments.callee;