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

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

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

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

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


当前回答

你应该在js中使用typeOf操作符。

var a=function(){
    alert("fun a");
}
alert(typeof a);// alerts "function"

其他回答

如果你使用Lodash,你可以用_.isFunction来实现。

_.isFunction(function(){});
// => true

_.isFunction(/abc/);
// => false

_.isFunction(true);
// => false

_.isFunction(null);
// => false

如果value是一个函数,该方法返回true,否则返回false。

jQuery(3.3版已弃用)参考

$.isFunction(functionName);

AngularJS参考

angular.isFunction(value);

Lodash参考

_.isFunction(value);

强调参考

_.isFunction(object); 

Node.js自v4.0.0参考版起已弃用

var util = require('util');
util.isFunction(object);

你应该在js中使用typeOf操作符。

var a=function(){
    alert("fun a");
}
alert(typeof a);// alerts "function"

有更多的浏览器支持,也包括异步函数可以是:

const isFunction = value => value && (Object.prototype.toString.call(value) === "[object Function]" || "function" === typeof value || value instanceof Function);

然后像这样测试它:

isFunction(isFunction); //true
isFunction(function(){}); //true
isFunction(()=> {}); //true
isFunction(()=> {return 1}); //true
isFunction(async function asyncFunction(){}); //true
isFunction(Array); //true
isFunction(Date); //true
isFunction(Object); //true
isFunction(Number); //true
isFunction(String); //true
isFunction(Symbol); //true
isFunction({}); //false
isFunction([]); //false
isFunction("function"); //false
isFunction(true); //false
isFunction(1); //false
isFunction("Alireza Dezfoolian"); //false

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

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