sandip chitale's blog    Sandip Chitale's blog (scblog)
NOTE: I have moved many of my modules to NetBeans Plugin Portal . Please check there for latest versions of modules described on this blog.
20071224 Monday December 24, 2007

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 Comments [2]










« December 2007 »
SunMonTueWedThuFriSat
      
1
2
4
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
22
23
25
27
28
29
30
31
     
Today

Get NetBeans 5.5

Locations of visitors to this page

Today's Page Hits: 459


XML
All
/Creator
/General
/Hobby
/Java
/JavaScript
/Mozilla
/NetBeans
/Ubuntu
/VisualWeb
/VisualWebPack
/Web 2.0

XML
All
/Creator
/General
/Hobby
/Java
/JavaScript
/Mozilla
/NetBeans
/Ubuntu
/VisualWeb
/VisualWebPack
/Web 2.0

scblog
scblog