How can I check if a javascript variable is functi

2018-12-31 19:48发布

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);

How can I check if the variable 'a' is of type function in the way defined above?

标签: javascript
17条回答
萌妹纸的霸气范
2楼-- · 2018-12-31 20:28

Since node v0.11 you can use the standard util function :

var util = require('util');
util.isFunction('foo');
查看更多
十年一品温如言
3楼-- · 2018-12-31 20:30

An other simply way:

var fn = function () {}
if (fn.constructor === Function) {
  // true
} else {
  // false
}
查看更多
素衣白纱
4楼-- · 2018-12-31 20:31

I think you can just define a flag on the Function prototype and check if the instance you want to test inherited that

define a flag:

Function.prototype.isFunction = true; 

and then check if it exist

var foo = function(){};
foo.isFunction; // will return true

The downside is that another prototype can define the same flag and then it's worthless, but if you have full control over the included modules it is the easiest way

查看更多
步步皆殇っ
5楼-- · 2018-12-31 20:31

you should use typeOf operator in js.

var a=function(){
    alert("fun a");
}
alert(typeof a);// alerts "function"
查看更多
梦醉为红颜
6楼-- · 2018-12-31 20:34

jQuery (deprecated since version 3.3) Reference

$.isFunction(functionName);

AngularJS Reference

angular.isFunction(value);

Lodash Reference

_.isFunction(value);

Underscore Reference

_.isFunction(object); 

Node.js deprecated since v4.0.0 Reference

var util = require('util');
util.isFunction(object);
查看更多
登录 后发表回答