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. 
Comments:

Hi there,

Great piece of code.
I tried to use it and this is what i came up with:
1) it won't work in IE.
2) it will display only the part of the stack that is in the current .js file as the code. This means that if my system works with multiple files, i won't be able to see the stack trace from the other files.

Anyway,
I did work around (1) but am stuck on problem (2).

Any chance you can give me a hint?

Thanks.

Posted by Lior on January 22, 2008 at 09:11 PM PST #

@Lior

Can you please share with us how you made it work on IE.
Actually 2 works for me.

Posted by Sandip on January 22, 2008 at 11:33 PM PST #

Post a Comment:
Comments are closed for this entry.
About

sandipchitale

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today