So my traffic went kaboom yesterday (most traffic I’ve ever gotten – period) because my post made the home page of reddit apparently. This is novel and I welcome all those viewers to my little corner of the tubes. What’s interesting though is the conversation going on over there.
I’ll point out that the code in question (on a Function.apply method for IE5) that I understand why Microsoft would write such a hack, as IE5 doesn’t have a suitable method for deferment and they can’t just ignore those users. It’s easy for me and others to be entertained by such a hack, but it’s not like I suggested an alternative.
To be frank, I simply wouldn’t even try to. IE5 is 9 and a half years old and I don’t envy anyone who has to support it. I was amused by the method I posted, but hey, it works, and that’s about all that really matters.
Still, that said, it is possible to implement a more elegant apply method for IE5. Here’s an example from google’s code base:
if (!Function.prototype.apply) {
Function.prototype.apply = function(oScope, args) {
var sarg = [];
var rtrn, call;
if (!oScope) oScope = goog.global;
if (!args) args = [];
for (var i = 0; i < args.length; i++) {
sarg[i] = 'args[' + i + ']';
}
call = 'oScope.__applyTemp__.peek().(' + sarg.join(',') + ');';
if (!oScope['__applyTemp__']) {
oScope['__applyTemp__'] = [];
}
oScope['__applyTemp__'].push(this);
rtrn = eval(call);
oScope['__applyTemp__'].pop();
return rtrn;
};
}
Now, one could argue that this is an ugly hack too. Using eval and whatnot. But there are two things about it that make it a better solution in my book (and to be clear, there are no doubt even better ones out there – I haven’t searched that hard). Those two things are:
- The function isn’t limited by the number of arguments you can pass it. In the MSFT version, if you passed in more than 10 arguments, you just got a ridiculous error.
- More importantly, it defines apply only if it doesn’t already exist. The MSFT code defines its method for everyone and it’s not even on the Function prototype. Rather than testing to see if the method they needed exists, they opt to just use a non-native hack that uses eval.
It’s easy to call this one from the sidelines as being a ridiculous hack, but I genuinely sympathize with someone who has to support JavaScript on IE5. That said, acting like every browser is IE5 is just inflicting pain one’s self for no good reason.