Check if a variable is of function type

后端 未结 18 1643
北海茫月
北海茫月 2020-11-22 15:37

Suppose I have any variable, which is defined as follows:

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

I want a function which checks if the type

18条回答
  •  一整个雨季
    2020-11-22 16:27

    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
    

提交回复
热议问题