Thursday, June 30th, 2005
Code: Try.these(func1, func2, func3)
<>p>In the “cool JavaScript snippets” department, we delve into the Prototype library for a nice function which tries to fire and forget through a set of operations.Defining Try.these
var Try = {
these: function() {
var returnValue;
for (var i = 0; i < arguments.length; i++) {
var lambda = arguments[i];
try {
returnValue = lambda();
break;
} catch (e) {}
}
return returnValue;
}
}
Example using the function
var Ajax = {
getTransport: function() {
return Try.these(
function() {return new ActiveXObject('Msxml2.XMLHTTP')},
function() {return new ActiveXObject('Microsoft.XMLHTTP')},
function() {return new XMLHttpRequest()}
) || false;
},
emptyFunction: function() {}
}








That code would be much easier to read with formatting!
Cool. Basically a Chain of Responsibility. You could make it slightly more structured to allow individual handlers to reject the request in ways other than throwing an error, but I’d not really thought of using this pattern in JavaScript.