检查变量是否为函数类型 [英] Check if a variable is of function type

查看:69
本文介绍了检查变量是否为函数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有任何变量,其定义如下:

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是否为Function类型?

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]';
}

这篇关于检查变量是否为函数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆