Archive for February, 2009

JavaScript function definition inside a with() block: Firefox is the oddball

February 14th, 2009

I came across yet another browser discrepancy with a rather obscure scenario: A function declaration within a with block:

var obj = { a: 1 };

with (obj) {
    function foo() {
        return typeof a;
    }
}

alert(foo()); // alerts "number" on Firefox, "undefined" on others

This exposes the object properties to the function scope only on Firefox. On all other browsers that I’ve tested with (IE, Safari, Opera and Chrome), the property isn’t visible inside the function.


Browser discrepancies when calling toString() on a JavaScript function with comments

February 6th, 2009

I’ve been working on extracting some text out of a given JavaScript function when I realized that toString() may return parts of the original comments, depending on the browser. I’ve done a quick test to capture the behaviour 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 "...";
}