在我的特殊情况下:

callback instanceof Function

or

typeof callback == "function"

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

额外的资源:

花园typeof vs instanceof


当前回答

typeof:根据MDN文档,typeof是一个一元操作符,返回指示未求值操作数类型的字符串。

在字符串原语和字符串对象的情况下,typeof返回如下:

const a = "I'm a string primitive";
const b = new String("I'm a String Object");

typeof a; --> returns 'string'
typeof b; --> returns 'object'

Instanceof:是一个二进制操作符,接受一个对象和一个构造函数。它返回一个布尔值,指示对象的原型链中是否有给定的构造函数。

当应用于上面的string实例时,并与string进行比较,它的行为如下:

const a = "I'm a string primitive";
const b = new String("I'm a String Object");

a instanceof String; --> returns false
b instanceof String; --> returns true

参考:https://bambielli.com/til/2017-06-18-typeof-vs-instanceof/

其他回答

没有必要用上面的大量例子来压倒你,只需要记住两个观点:

typeof var; is an unary operator will return the original type or root type of var. so that it will return primitive types(string, number, bigint, boolean, undefined, and symbol) or object type. in case of higher-level object, like built-in objects (String, Number, Boolean, Array..) or complex or custom objects, all of them is object root type, but instance type built base on them is vary(like OOP class inheritance concept), here a instanceof A - a binary operator - will help you, it will go through the prototype chain to check whether constructor of the right operand(A) appears or not.

所以当你想检查“根类型”或使用基元变量时,使用“typeof”,否则使用“instanceof”。

Null是一种特殊情况,它看起来很原始,但实际上是object的特殊情况。使用a === null代替检查null。

另一方面,function也是一种特殊情况,它是内置对象,但typeof返回函数

正如你所看到的,instanceof必须遍历原型链,而typeof只检查根类型一次,所以很容易理解为什么typeof比instanceof快

其他重要的实际差异:

// Boolean

var str3 = true ;

alert(str3);

alert(str3 instanceof Boolean);  // false: expect true  

alert(typeof str3 == "boolean" ); // true

// Number

var str4 = 100 ;

alert(str4);

alert(str4 instanceof Number);  // false: expect true   

alert(typeof str4 == "number" ); // true

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

callback instanceof Function

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

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

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

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

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

两者在功能上相似,因为它们都返回类型信息,但我个人更喜欢instanceof,因为它比较的是实际类型而不是字符串。类型比较不容易出现人为错误,而且技术上更快,因为它比较内存中的指针,而不是整个字符串的比较。