假设我有任何变量,定义如下:
var a = function() {/* Statements */};
我想要一个检查变量类型是否像函数一样的函数。即:
function foo(v) {if (v is function type?) {/* do something */}};
foo(a);
如何检查变量a
是否为Function
上述定义的类型?
假设我有任何变量,定义如下:
var a = function() {/* Statements */};
我想要一个检查变量类型是否像函数一样的函数。即:
function foo(v) {if (v is function type?) {/* do something */}};
foo(a);
如何检查变量a
是否为Function
上述定义的类型?
The below seems to work for me as well (tested from node.js
):
var isFunction = function(o) {
return Function.prototype.isPrototypeOf(o);
};
console.log(isFunction(function(){})); // true
console.log(isFunction({})); // false
I found that when testing native browser functions in IE8, using toString
, instanceof
, and typeof
did not work. Here is a method that works fine in IE8 (as far as I know):
function isFn(f){
return !!(f && f.call && f.apply);
}
//Returns true in IE7/8
isFn(document.getElementById);
Alternatively, you can check for native functions using:
"getElementById" in document
Though, I have read somewhere that this will not always work in IE7 and below.
If you use Lodash you can do it with _.isFunction.
_.isFunction(function(){});
// => true
_.isFunction(/abc/);
// => false
_.isFunction(true);
// => false
_.isFunction(null);
// => false
This method returns true
if value is a function, else false
.
Something with more browser support and also include async functions could be:
const isFunction = value => value && (Object.prototype.toString.call(value) === "[object Function]" || "function" === typeof value || value instanceof Function);
and then test it like:
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
An other simply way:
var fn = function () {}
if (fn.constructor === Function) {
// true
} else {
// false
}
Try the instanceof
operator: it seems that all functions inherit from the Function
class:
// Test data
var f1 = function () { alert("test"); }
var o1 = { Name: "Object_1" };
F_est = function () { };
var o2 = new F_est();
// Results
alert(f1 instanceof Function); // true
alert(o1 instanceof Function); // false
alert(o2 instanceof Function); // false
var foo = function(){};
if (typeof foo === "function") {
alert("is function")
}
Underscore.js使用更精细但性能更高的测试:
_.isFunction = function(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
};
请参阅:http://jsperf.com/alternative-isfunction-implementations
编辑:更新的测试表明typeof可能更快,请参阅http://jsperf.com/alternative-isfunction-implementations/4
if (typeof v === "function") {
// do something
}
you should use
typeOf
operator in js.