在我的特殊情况下:

callback instanceof Function

or

typeof callback == "function"

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

额外的资源:

花园typeof vs instanceof


当前回答

两者在功能上相似,因为它们都返回类型信息,但我个人更喜欢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/

我认为,当callback是Function的子类型时,instanceof也可以工作

两者在功能上相似,因为它们都返回类型信息,但我个人更喜欢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快

使用typeof的一个很好的理由是变量可能是未定义的。

alert(typeof undefinedVariable); // alerts the string "undefined"
alert(undefinedVariable instanceof Object); // throws an exception

使用instanceof的一个很好的理由是变量可能为空。

var myNullVar = null;
alert(typeof myNullVar ); // alerts the string "object"
alert(myNullVar  instanceof Object); // alerts "false"

所以在我看来,这取决于你在检查什么类型的数据。