在我的特殊情况下:

callback instanceof Function

or

typeof callback == "function"

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

额外的资源:

花园typeof vs instanceof


当前回答

instanceof将不适用于原语,例如"foo" instanceof String将返回false,而typeof "foo" == " String "将返回true。

另一方面,当涉及到自定义对象(或类,无论你想叫它们什么)时,typeof可能不会做你想做的事情。例如:

function Dog() {}
var obj = new Dog;
typeof obj == 'Dog' // false, typeof obj is actually "object"
obj instanceof Dog  // true, what we want in this case

函数碰巧既是“函数”原语,又是“函数”的实例,这有点奇怪,因为它不像其他原语类型那样工作,例如。

(typeof function(){} == 'function') == (function(){} instanceof Function)

but

(typeof 'foo' == 'string') != ('foo' instanceof String)

其他回答

var newObj = new Object;//对象实例 var newProp = "I'm xgqfrms!"/ /定义属性 var newFunc = function(name){//定义函数 Var hello ="hello, "+ name +"!"; 返回你好; } //添加属性newObj.info = newProp newObj。//添加函数 console.log(newObj.info) //我是xgqfrms! console.log(newObj.func("ET")) //你好,ET! console.log(newObj instanceof Object); / /正确的 console.log (typeof (newObj)); / /“对象”

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/

准确地说 应该在通过构造函数(通常是自定义类型)创建值的地方使用Instanceof。

var d = new String("abc")

而typeof用于检查仅由赋值创建的值,例如

var d = "abc"

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

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