Callstack information in JavaScript
I have started hacking JavaScript. It has been an interesting learning experience and quite different from Java coding. However some things remain same...here is a function to get the information about current call stack:
/**
* This function returns an array of objects that contains information about the current call stack.
*/
function callstack() {
var stackFrameStrings = new Error().stack.split('\n');
stackFrameStrings.splice(0,2);
var stackFrames = [];
for (var i in stackFrameStrings) {
var stackFrame = stackFrameStrings[i].split('@');
if (stackFrame && stackFrame.length == 2) {
stackFrames.push(
{
functionName: stackFrame[0],
functionSource: eval(stackFrame[0].replace(/[(][^)]*[)]/,'')),
fileName: stackFrame[1].match(/(.*):(\d+)$/)[1],
lineNumber: stackFrame[1].match(/(.*):(\d*)$/)[2]
}
);
}
}
return stackFrames;
}
NOTE: Tested in Firefox.
It uses a mechanism very similar to Java's new Throwable().getStackTrace() to get information about the current call stack. It uses the JavaScript Error object which happens to have a property called stack. Example usage:
function called() {
var cs = callstack();
alert('Self: ' + cs[0].functionName);
alert('Caller: ' + cs[1].functionName);
}
function caller() {
called();
}
caller();
This displays two alert dialogs:
Self: called()
Caller: caller()
Please let me know if there is a better way to get similar information.
Posted by sandipchitale
( Dec 24 2007, 02:02:30 PM PST ) Permalink