在我的特殊情况下:

callback instanceof Function

or

typeof callback == "function"

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

额外的资源:

花园typeof vs instanceof


当前回答

当检查一个函数时,必须总是使用typeof。

区别在于:

var f = Object.create(Function);

console.log(f instanceof Function); //=> true
console.log(typeof f === 'function'); //=> false

f(); // throws TypeError: f is not a function

这就是为什么决不能使用instanceof来检查函数。

其他回答

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)); / /“对象”

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

var d = new String("abc")

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

var d = "abc"

使用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"

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

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

还有一种情况是你只能用instanceof进行排序——它返回true或false。使用typeof你可以得到typeof提供的东西