views:

360

answers:

3

Does JavaScript have a mechanism for determining the line number of the currently executing statement (and if so, what is it)?

+6  A: 

var thisline = new Error().lineNumber

If that doesn't work in whatever environment you're using, you can try:

var stack = new Error().stack

Then hunt through the stack for the line number.

z5h
Will not work in IE, the `lineNumber` property doesn't exist on error objects. Neither does `stack` :-)
Andy E
there is a line number somewhere on IE. I know this because when my javascript throws an error is says it's on a line with a number greater than 100 million.
Malfist
+1  A: 

you can try:

window.onerror = handleError;
function handleError(err, url, line){
   alert(err + '\n on page: ' + url + '\n on line: ' + line);
}

then throw an error where you want to know (not overly desired, but it might help you if you are debugging.

Note: window.onerror isn't defined/handled in WebKit or Opera (last time I checked)

scunliffe
Note that window.onerror doesn't work in webkit: https://bugs.webkit.org/show_bug.cgi?id=8519
Annie
Interesting. You could even create a special function `throwAndResume(resumeFunction);` that would store resumeFunction, throw the error, and in your error handler log the details then call resumeFunction to continue your program.
z5h
A: 

You can try to parse a source of a function to seek some marks.
Here is a quick example (yes, it's messed a little).

function foo()  
{       
    alert(line(1));
    var a;
    var b;      
    alert(line(2));
}   
foo();

function line(mark)
{
    var token = 'line\\(' + mark + '\\)';       
    var m = line.caller.toString().match(
        new RegExp('(^(?!.*' + token + '))|(' + token + ')', 'gm')) || [];
    var i = 0;
    for (; i < m.length; i++) if (m[i]) break;
    return i + 1;
}
Mikhail Nasyrov