在我的特殊情况下:
callback instanceof Function
or
typeof callback == "function"
这有关系吗,有什么区别?
额外的资源:
花园typeof vs instanceof
在我的特殊情况下:
callback instanceof Function
or
typeof callback == "function"
这有关系吗,有什么区别?
额外的资源:
花园typeof vs 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"
所以在我看来,这取决于你在检查什么类型的数据。
其他回答
显著的实际差异:
var str = 'hello word';
str instanceof String // false
typeof str === 'string' // true
别问我为什么。
使用instanceof,因为如果你改变了类的名字,你会得到一个编译器错误。
考虑到性能,您最好使用typeof 对于典型的硬件,如果您创建一个具有1000万次迭代循环的脚本 指令:typeof STR == 'string'将花费9毫秒 而'string' instanceof string将花费19毫秒
我认为,当callback是Function的子类型时,instanceof也可以工作
准确地说 应该在通过构造函数(通常是自定义类型)创建值的地方使用Instanceof。
var d = new String("abc")
而typeof用于检查仅由赋值创建的值,例如
var d = "abc"