在我的特殊情况下:

callback instanceof Function

or

typeof callback == "function"

这有关系吗,有什么区别?

额外的资源:

花园typeof vs instanceof


当前回答

我建议使用原型的callback.isFunction()。

他们已经找出了其中的区别,你可以相信他们的理由。

我猜其他JS框架也有这样的东西。

instanceOf不会在其他窗口中定义的函数上工作,我相信。 它们的函数和你的窗口函数不同。

其他回答

我从小接受严格的面向对象教育

callback instanceof Function

字符串容易出现我糟糕的拼写或其他拼写错误。而且我觉得读起来更好。

使用instanceof,因为如果你改变了类的名字,你会得到一个编译器错误。

根据MDN关于typeof的文档,用"new"关键字实例化的对象类型为'object':

typeof 'bla' === 'string';

// The following are confusing, dangerous, and wasteful. Avoid them.
typeof new Boolean(true) === 'object'; 
typeof new Number(1) === 'object'; 
typeof new String('abc') === 'object';

而关于instanceof点的文档说明:

const objectString = new String('String created with constructor');
objectString instanceOf String; // returns true
objectString instanceOf Object; // returns true

因此,如果有人想检查,例如,某东西是一个字符串,无论它是如何创建的,最安全的方法是使用instanceof。

考虑到性能,您最好使用typeof 对于典型的硬件,如果您创建一个具有1000万次迭代循环的脚本 指令:typeof STR == 'string'将花费9毫秒 而'string' instanceof string将花费19毫秒

使用instanceof自定义类型:

var ClassFirst = function () {};
var ClassSecond = function () {};
var instance = new ClassFirst();
typeof instance; // object
typeof instance == 'ClassFirst'; // false
instance instanceof Object; // true
instance instanceof ClassFirst; // true
instance instanceof ClassSecond; // false 

对于简单的内置类型使用typeof:

'example string' instanceof String; // false
typeof 'example string' == 'string'; // true

'example string' instanceof Object; // false
typeof 'example string' == 'object'; // false

true instanceof Boolean; // false
typeof true == 'boolean'; // true

99.99 instanceof Number; // false
typeof 99.99 == 'number'; // true

function() {} instanceof Function; // true
typeof function() {} == 'function'; // true

对于复杂的内置类型使用instanceof:

/regularexpression/ instanceof RegExp; // true
typeof /regularexpression/; // object

[] instanceof Array; // true
typeof []; //object

{} instanceof Object; // true
typeof {}; // object

最后一个有点棘手:

typeof null; // object