Javascript 检查变量是否为函数类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5999998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:49:08  来源:igfitidea点击:

Check if a variable is of function type

javascript

提问by Jesufer Vn

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. :

我想要一个函数来检查变量的类型是否类似于函数。IE :

function foo(v) {if (v is function type?) {/* do something */}};
foo(a);

How can I check if the variable ais of type Functionin the way defined above?

如何检查变量a是否属于Function上述定义的类型?

采纳答案by Alex Grande

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.

当然下划线的方式更有效,但是当效率不是问题时,检查的最佳方法是写在@Paul Rosania 链接的下划线页面上。

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

受下划线启发,最终的 isFunction 函数如下:

function isFunction(functionToCheck) {
 return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}

回答by selbie

if (typeof v === "function") {
    // do something
}

回答by Paul Rosania

Underscore.jsuses a more elaborate but highly performant test:

Underscore.js使用了一个更复杂但性能更高的测试:

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

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

请参阅:http: //jsperf.com/alternative-isfunction-implementations

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

编辑:更新的测试表明 typeof 可能更快,请参阅http://jsperf.com/alternative-isfunction-implementations/4

回答by dalimian

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 typeofis 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
  1. 最好的办法是:
    function foo(v) {if (v instanceof Function) {/* do something */} };
    
    
    最高效(无字符串比较)和优雅的解决方案——instanceof 运算符在浏览器中已经被支持很长时间了,所以别担心——它可以在 IE 6 中工作。
  2. 下一个最好的方法是:
    function foo(v) {if (typeof v === "function") {/* do something */} };
    
    
    缺点typeof是它很容易出现无声失败,不好,所以如果你有一个错字(例如“finction”) - 在这种情况下,`if` 只会返回 false 并且你不会知道你有错误,直到稍后你的代码
  3. 下一个最好的方法是:
    function isFunction(functionToCheck) {
        var getType = {};
        return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
    }
    
    
    这与解决方案 #1 或 #2 相比没有优势,但可读性要差得多。这个的改进版本是
    function isFunction(x) {
        return Object.prototype.toString.call(x) == '[object Function]';
    }
    
    
    但仍然比解决方案#1 少很多语义

回答by Cesar Loachamin

jQuery(deprecated since version 3.3) Reference

jQuery(自 3.3 版起已弃用)参考

$.isFunction(functionName);

AngularJSReference

AngularJS参考

angular.isFunction(value);

LodashReference

Lodash参考

_.isFunction(value);

UnderscoreReference

下划线参考

_.isFunction(object); 

Node.jsdeprecated since v4.0.0 Reference

Node.js从 v4.0.0 开始弃用参考

var util = require('util');
util.isFunction(object);

回答by dandean

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

@grandecomplex:您的解决方案相当冗长。写成这样就清楚多了:

function isFunction(x) {
  return Object.prototype.toString.call(x) == '[object Function]';
}

回答by wsc

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

回答by wsc

Try the instanceofoperator: it seems that all functions inherit from the Functionclass:

试试instanceof运算符:似乎所有函数都继承自Function该类:

// 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

回答by Alireza

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

回答by GuillaumeL

An other simply way:

另一种简单的方法:

var fn = function () {}
if (fn.constructor === Function) {
  // true
} else {
  // false
}