Saturday 6 March 2010

Yesterday I discovered a defect in Javascript in IE6: sometimes when an error is thrown the function simply returns instead! It occurs when you make function global by assigning it as a property of the global object, such as when you're using the module pattern:

(function() {

var GLOBAL = this;

// private functions
function foo() {\\...};

// public functions
GLOBAL.myFn = function() {\\...};

})();


I boiled it down to the following simple example:

this.myTest = function(x)
{
throw new Error("foo");
}

function runMyTest()
{
try
{
myTest("anything");
alert("Simply returned");
}
catch(e)
{
alert("caught");
return;
}
alert("Not caught");
}

In IE6 you get the "Simply returned" and "Not caught" alerts!!

Considering IE6's age I was surprised not to find any mention of this on the web, but there was a related problem reported at http://cappuccino.org/discuss/2010/03/01/internet-explorer-global-variables-and-stack-overflows/

The simplest solution for both problems (though not an example of clear code) is to simply rely upon implicit global variables, i.e.

(function() {

// private functions
function foo() {\\...};

// public functions
myFn = function() {\\...};

})();