Suppose I have any variable, which is defined as follows:
var a = function() {/* Statements */};
I want a function which checks if the type
Sure underscore's way is more efficient, but the best way to check, when efficiency isn't an issue, is written on underscore's page linked by @Paul Rosania.
Inspired by underscore, the final isFunction function is as follows:
function isFunction(functionToCheck) {
return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}
@grandecomplex: There's a fair amount of verbosity to your solution. It would be much clearer if written like this:
function isFunction(x) {
return Object.prototype.toString.call(x) == '[object Function]';
}
Try the instanceof
operator: it seems that all functions inherit from the Function
class:
// Test data
var f1 = function () { alert("test"); }
var o1 = { Name: "Object_1" };
F_est = function () { };
var o2 = new F_est();
// Results
alert(f1 instanceof Function); // true
alert(o1 instanceof Function); // false
alert(o2 instanceof Function); // false
if (typeof v === "function") {
// do something
}
An other simply way:
var fn = function () {}
if (fn.constructor === Function) {
// true
} else {
// false
}
There are several ways so I will summarize them all
function foo(v) {if (v instanceof Function) {/* do something */} };Most performant (no string comparison) and elegant solution - the instanceof operator has been supported in browsers for a very long time, so don't worry - it will work in IE 6.
function foo(v) {if (typeof v === "function") {/* do something */} };disadvantage of
typeof
is that it is susceptible to silent failure, bad, so if you have a typo (e.g. "finction") - in this case the `if` will just return false and you won't know you have an error until later in your code
function isFunction(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; }This has no advantage over solution #1 or #2 but is a lot less readable. An improved version of this is
function isFunction(x) { return Object.prototype.toString.call(x) == '[object Function]'; }but still lot less semantic than solution #1