It is often very useful to determine the call-stack when debugging client-side JavaScript code. Here is a simple solution populating the call stack into a string.
The sample code below has two components: travel up the call stack by accessing the caller of each function, and process the arguments of each entry in the stack. The getCallStack() function can be used in many contexts, including for instrumentation of event propagation.
JavaScript call stack retrieval function.
function getCallStack() {
var f = getCallStack, result = "Call stack:\n\n";
while ((f = f.caller) !== null) {
if (f.toString().match(/^function (\w+)\(/) != null)
result += f.toString().match(/^function (\w+)\(/)[1] + parseArguments(f.arguments) + "\n";
else result += 'anonymous' + parseArguments(f.arguments) + "\n";
}
return result;
}
function parseArguments(a) {
var result = [];
for (var i = 0; i < a.length; i++) {
if (typeof a[i] === 'string')
result.push("\"" + a[i] + "\"");
else result.push(a[i]);
}
return "(" + result.join(", ") + ")";
}
Leave a comment