node.js 节点js检查var是否是一个函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13053788/
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-09-02 16:31:48  来源:igfitidea点击:

Node js check if a var is a function

node.js

提问by Rolando Corratge Nieves

Possible Duplicate:
How can I check if a javascript variable is function type?

可能重复:
如何检查 javascript 变量是否为函数类型?

How i check if a variable is a function for Array exist Array.isArray()but Function.isFunctiondos'nt exist

我如何检查变量是否是 Array 的函数Array.isArray()Function.isFunction不存在

回答by paul

if (typeof variable === 'function') {
    // do something
}

回答by Manu Letroll

You can use the instanceofoperator.

您可以使用instanceof运算符。

var fn = function() {};
var result = fn instanceof Function; // result will be true

It also respects prototypal inheritance.

它还尊重原型继承。

回答by BadCanyon

Underscore.js is a library that has a lot of useful helpers, like the one you're looking for.

Underscore.js 是一个库,它有很多有用的助手,就像你正在寻找的那样。

http://underscorejs.org/

http://underscorejs.org/

_ = require('underscore');

var aFunction = function() { };
var notFunction = 'Not a function';

_.isFunction(aFunction); // true
_.isFunction(notFunction); // false

回答by orustam

var fn = function() {},
    toString = Object.prototype.toString;

first way:

if( toString.call( function(){} ) === '[object Function]' ) {
    //if is Function do something...
}

second way:

if( fn.constructor.name = 'Function' ) {
    //if is Function do something...
}

Hope it helps cheers:)!

希望它有助于欢呼:)!