Check if a variable is of function type

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

    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.

    Inspired by underscore, the final isFunction function is as follows:

    function isFunction(functionToCheck) {
     return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
    }
    
    0 讨论(0)
  • 2020-11-22 16:21

    @grandecomplex: There's a fair amount of verbosity to your solution. It would be much clearer if written like this:

    function isFunction(x) {
      return Object.prototype.toString.call(x) == '[object Function]';
    }
    
    0 讨论(0)
  • 2020-11-22 16:22

    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
    
    0 讨论(0)
  • 2020-11-22 16:23
    if (typeof v === "function") {
        // do something
    }
    
    0 讨论(0)
  • 2020-11-22 16:23

    An other simply way:

    var fn = function () {}
    if (fn.constructor === Function) {
      // true
    } else {
      // false
    }
    
    0 讨论(0)
  • 2020-11-22 16:25

    There are several ways so I will summarize them all

    1. Best way is:
      
      function foo(v) {if (v instanceof Function) {/* do something */} };
      
      
      Most performant (no string comparison) and elegant solution - the instanceof operator has been supported in browsers for a very long time, so don't worry - it will work in IE 6.
    2. Next best way is:
      
      function foo(v) {if (typeof v === "function") {/* do something */} };
      
      
      disadvantage of typeof is that it is susceptible to silent failure, bad, so if you have a typo (e.g. "finction") - in this case the `if` will just return false and you won't know you have an error until later in your code
    3. The next best way is:
      
      function isFunction(functionToCheck) {
          var getType = {};
          return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
      }
      
      
      This has no advantage over solution #1 or #2 but is a lot less readable. An improved version of this is
      
      function isFunction(x) {
          return Object.prototype.toString.call(x) == '[object Function]';
      }
      
      
      but still lot less semantic than solution #1
    0 讨论(0)
提交回复
热议问题