假设有任意变量,定义如下:

var a = function() {/* Statements */};

我想要一个函数来检查变量的类型是否为类函数。例如:

function foo(v) {if (v is function type?) {/* do something */}};
foo(a);

我怎样才能检查变量a是否为上述定义的函数类型?


当前回答

如果你正在寻找一个简单的解决方案:

 function isFunction(value) {
   return value instanceof Function
}

其他回答

有几种方法,所以我将把它们都总结一下

Best way is: 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. Next best way is: 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 The next best way is: 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

另一种简单的方法:

var fn = function () {}
if (fn.constructor === Function) {
  // true
} else {
  // false
}

注意这一点:

typeof Object === "function" // true.
typeof Array  === "function" // true

@grandecomplex:你的解决方案相当冗长。如果这样写会更清楚:

function isFunction(x) {
  return Object.prototype.toString.call(x) == '[object Function]';
}

js使用了一个更精细但高性能的测试:

_.isFunction = function(obj) {
  return !!(obj && obj.constructor && obj.call && obj.apply);
};

参见:https://jsben.ch/B6h73

编辑:更新的测试表明typeof可能更快,参见https://jsben.ch/B6h73