A quick snippet that I spotted within the up-and-coming Johnson project (A Ruby/Spidermonkey hybridization.):
(function(){ this.__defineGetter__("__FILE__", function() { return (new Error).stack.split("\n")[2].split("@")[1].split(":").slice(0,-1).join(":"); }); })();
The above defines a global variable __FILE__ which, when called, returns the file name of the current JavaScript file. It’s defined using a getter in particular so that the proper file name will be determined no matter what file it’s called in (so you can safely include the above in a library file and it’ll still report the correct, current, filename).
Currently the above will only work in Spidermonkey as only it supports the .stack stacktrace Error property. If there are reasonable alternatives for WebKit or Opera (which also support __defineGetter__) let me know.
x (June 7, 2008 at 9:56 pm)
dirty but works in latest opera (didn’t test in older versions)-
http://collabedit.com/display?id=9083fa23df7b7e65ef65328c5a77b439
x (June 7, 2008 at 10:33 pm)
pastebin url: http://js.pastebin.org/42297 (forgot that anyone can edit on collabedit.com)
Corkie (June 7, 2008 at 11:06 pm)
clever :)
I like it
markus (June 8, 2008 at 3:26 am)
really nice
Jonathan Watt (June 8, 2008 at 7:22 am)
Where’s the __LINE__ getter? :)
Roshan Bhattarai (June 9, 2008 at 11:14 am)
wow……thanks for this…I like it…
Justin Meyer (June 11, 2008 at 12:47 am)
Sweet. Are you involved with the Johnson project? If not, I’m amazed how you find things like this.