For simple javascript debugging I’ll use alerts to show variable values and the like. Is there a way to get the current call stack in javascript to be able to display it in an alert?
Thanks.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Quick and dirty in Gecko-based browsers:
You can also manually trawl some of the stack using Function.prototype.caller:
One (possibly large) caveat of the .caller trick is that it doesn’t handle recursion —
.callerlooks from the top of the stack downward to find the first instance of the function in the stack and then returns its immediate caller, so without being careful you can loop infinitely looking up callers.Another caveat to
calleris that, going forward, if any of your code uses ECMAScript 5’s strict mode, thecallerproperty of strict mode functions (or of functions which have themselves been called from strict mode functions) is a so-called “poison pill” which throws aTypeErrorwhen accessed. Thecallerproperty of “bound” functions (those created by ES5’sFunction.prototype.bindmethod) is also a poison pill. These restrictions break the generic stack-walking algorithm, although one could imagine use-specific ways to work around this (entry and exit annotating functions, perhaps).Do note that stack-walking like this isn’t a great idea in production code (as a quick hack for debugging it’s fine, tho); at the moment walking up the stack as in the latter example is somewhat expensive in Mozilla’s JS engine, and it’ll probably throw you out of machine code and back into interpreted code. Also, the stack-walk is O(n2), which might matter if you tend to have complex, deep stacks.