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
2010-02-26 17:08:48
Will not work in IE, the `lineNumber` property doesn't exist on error objects. Neither does `stack` :-)
Andy E
2010-02-26 17:11:31
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
2010-02-26 17:17:47
+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
2010-02-26 18:22:27
Note that window.onerror doesn't work in webkit: https://bugs.webkit.org/show_bug.cgi?id=8519
Annie
2010-02-26 18:35:44
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
2010-02-26 18:37:20
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
2010-02-26 19:01:30