Browser discrepancies when calling toString() on a JavaScript function with comments
I had been working on parsing the source of JavaScript function instances when I realized that Function.prototype.toString() may return parts of the original comments in the source code, depending on the browser. I’ve done a quick test to capture the different behaviours of popular browsers.
Here’s my test script:
function/*post-keyword*/fn/*post-name*/()/*post-parens*/{
/*inside*/
}
document.write(fn.toString());
And here are the results I got on different browsers:
| Browser | post-keyword | post-name | post-parens | inside |
|---|---|---|---|---|
| Firefox | No | No | No | No |
| Safari | No | No | No | No |
| Chrome | No | No | Yes | Yes |
| IE | Yes | Yes | Yes | Yes |
| Opera | Yes | Yes | Yes | Yes |
And out of the browser context:
| Engine | post-keyword | post-name | post-parens | inside |
|---|---|---|---|---|
| JScript | Yes | Yes | Yes | Yes |
| Rhino | No | No | No | No |
While looking for the best solution to extract the parts that I need, I’ve implemented a workaround. Sort of. If blocking the problem can be considered a workaround:
var functionToStringHasComments = /PROBE/.test(function () {/*PROBE*/});
// ...
if (functionToStringHasComments) {
throw "...";
}