Wednesday, August 5, 2009

isFunction hacked, isCallable solution

After this post, and after some twit exchange with @kangax, and finally after my hack for my function itself, here I am with my definitive solution to know if a passed argument could be called.

var isCallable = (function(toString){
// The Latest WebReflection Proposal
// Recently Updated with "explicit" cast
// thanks to abozhilov for the test case
var s = toString.call(toString),
u = typeof u;
return typeof this.alert === "object" ?
function(f){
return s === toString.call(f) || (!!f && typeof f.toString == u && typeof f.valueOf == u && /^\s*\bfunction\b/.test("" + f));
}:
function(f){
return s === toString.call(f);
}
;
})(Object.prototype.toString);

Speed will be the same with every browser, IE will do some extra check only if passed argument is not a function.
The "native" case could be a performance greedy check and we do not like eval in any case.
The "isFunction" name is not appropriate, cause a function is not a Host Object, as is effectively alert, as example, in Internet Explorer.
isCallable simply gets the best from old proposal, threading edge cases in a specific way for the edge browser, Internet Explorer.
Enjoy!

No comments:

Post a Comment