Check if a variable is of function type

后端 未结 18 1401
北海茫月
北海茫月 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:11

    var foo = function(){};
    if (typeof foo === "function") {
      alert("is function")
    }

    0 讨论(0)
  • 2020-11-22 16:13

    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.

    0 讨论(0)
  • 2020-11-22 16:17

    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);
    
    0 讨论(0)
  • 2020-11-22 16:18

    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.

    0 讨论(0)
  • 2020-11-22 16:18

    The solution as some previous answers has shown is to use typeof. the following is a code snippet In NodeJs,

        function startx() {
          console.log("startx function called.");
        }
    
     var fct= {};
     fct["/startx"] = startx;
    
    if (typeof fct[/startx] === 'function') { //check if function then execute it
        fct[/startx]();
      }
    
    0 讨论(0)
  • 2020-11-22 16:20

    Underscore.js uses a more elaborate but highly performant test:

    _.isFunction = function(obj) {
      return !!(obj && obj.constructor && obj.call && obj.apply);
    };
    

    See: http://jsperf.com/alternative-isfunction-implementations

    EDIT: updated tests suggest that typeof might be faster, see http://jsperf.com/alternative-isfunction-implementations/4

    0 讨论(0)
提交回复
热议问题