如何检查javascript变量是否为函数类型? [英] How can I check if a javascript variable is function type?
本文介绍了如何检查javascript变量是否为函数类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有任何变量,其定义如下:
Suppose I have any variable, which is defined as follows:
var a = function() {/* Statements */};
我想要一个检查变量类型是否类似函数的函数。即:
I want a function which checks if the type of the variable is function-like. i.e. :
function foo(v) {if (v is function type?) {/* do something */}};
foo(a);
如何以上面定义的方式检查变量'a'是否为type函数?
How can I check if the variable 'a' is of type function in the way defined above?
推荐答案
当然,下划线的方式更有效率,但是当效率不是问题时,最好的检查方法是写在下划线上由@Paul Rosania链接的页面。
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.
受到下划线的启发,最终的isFunction函数如下:
Inspired by underscore, the final isFunction function is as follows:
function isFunction(functionToCheck) {
return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}
这篇关于如何检查javascript变量是否为函数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文