Monday, August 04, 2003

JavaScript Debugging


// Displays the name of the function
// that just called the given function
function CallerID( func )
{
    // Build the regular expression to extract the name
    var re = /function (\w*)/;

    // Get the code of the caller function
    var callerFunc = func.caller.toString();

    // Extract the name of the caller function from its code
    var nameOfCaller = callerFunc.match( re )[1];

    // Display the name of the caller function
    alert( nameOfCaller );
}


The function above can be used to figure out what called a JavaScript function. To use it call it from the function in question and pass the function to it. For example, the code below would create an alert that displays the name of the function that called myFunc().


function myFunc()
{
    CallerID( myFunc);
}