Problem:
How do I check if a value stored in a javascript variable is a function?
Solution:
While there are many ways to do this, the following code should work:
function isFunction(toCheck){
return toCheck != null
&& {}.toString.call(toCheck) == '[object Function]';
}
Notes:
Note that the first conditional, toCheck != null, may not be necessary. However, if null or nothing is passed to the function the result could be undefined otherwise (this was encountered, at least, in some older (or buggy?) implementations of javascript but might be a non-issue today -- feel free to test it out).
An alternative (and closely-related) method of checking is to directly call Object.prototype.toString.call() instead of instantiating an anonymous object.
No comments:
Post a Comment