The other day I realised I actually have not presented the proper shape of the final version of my isFunction()
function.
I stumbled upon yepnope.js project and started nosily browsing through the code on Github. If course I smugly noticed that isFunction()
in there is “no good”, just to quickly realise I have never published the proper implementation of its final and probably the best version. Here it is then:
[gist id=1121314]
Original article is here : https://dbj.org/?p=286
Update 13.Aug.11
Since Gareth insisteth (see the comments bellow), I can do nothing but oblige. Here is one much more robust version, which will work correctly, even in presence of most JavaScript comedians.
[wp-js-fiddle url=”http://jsfiddle.net/dbjdbj/a6wfrvcc/2/” style=”width:100%; height:600px; border:1px dotted #4173A0;”]
Enjoy. Even better: use.
6 thoughts on “isFunction(), final…”
Is this a joke I don’t get?
var isFunction = (function() {
var rx = /^\s*\bfunction\b/;
return function(f) {
return rx.test(f);
}
}());
isFunction(‘function(‘);
No it is not a joke. It is a question of attitude. If You want to break it with a joke You certainly can. Same as any other isFunction() implementation. There are few more jokes that jokers like. For example:
[sourcecode lang=”jscript”]
isFunction({ "toString: function () { return "function"’ } }) ;
isFunction({ "valueOf: function () { return "function"’ } }) ;
/*
or … is jQuery a "joke" if this is possible?
*/
$(document.createElement("SPAN"))
.parent().remove().html("Joker").text()
[/sourcecode]
My solutions are not good for jokers, this is for people who want to have short and fast isFunction() that will work in every browser.
//chrome 13.0.782.112 m
theJoker=/a/;
theJoker.valueOf=function() {
return ‘function”‘;
};
@Gareth, Your
theJoker
is not good enough to fool myisFunction4jokers()
:You have not read my previous comment carefully, it contains a better joker Gareth:
But, I do not see the point of complicating my utility function so that it works in the presence of great comedians?
@Dusan
Actually on the version of chrome I posted the regex object returns “function” so it would work regardless of the type check. My point is the original function was really bad since a string with “function” inside it would pass the check which is bound to cause problems if used in production code. The deeper problem with JavaScript is that nothing can be guaranteed in an environment you don’t control which I find interesting and can lead to problems you don’t foresee.
@Gareth
The original function was really good for everybody and their production code, but You. That is the point I am making. People don’t have time to write libraries that will work in the presence of JavaScript comedians. You helped me think of a consistent definition of a JavaScript comedian. Any person who writes JavaScript code like this one:
My final version is actually not necessary . The original version works quite OK, in real life scenarios.