在我的特殊情况下:
callback instanceof Function
or
typeof callback == "function"
这有关系吗,有什么区别?
额外的资源:
花园typeof vs instanceof
在我的特殊情况下:
callback instanceof Function
or
typeof callback == "function"
这有关系吗,有什么区别?
额外的资源:
花园typeof vs instanceof
当前回答
准确地说 应该在通过构造函数(通常是自定义类型)创建值的地方使用Instanceof。
var d = new String("abc")
而typeof用于检查仅由赋值创建的值,例如
var d = "abc"
其他回答
准确地说 应该在通过构造函数(通常是自定义类型)创建值的地方使用Instanceof。
var d = new String("abc")
而typeof用于检查仅由赋值创建的值,例如
var d = "abc"
尽管instanceof可能比typeof快一点,但我更喜欢第二个,因为它可能有这样的魔力:
function Class() {};
Class.prototype = Function;
var funcWannaBe = new Class;
console.log(funcWannaBe instanceof Function); //true
console.log(typeof funcWannaBe === "function"); //false
funcWannaBe(); //Uncaught TypeError: funcWannaBe is not a function
我认为,当callback是Function的子类型时,instanceof也可以工作
还有一种情况是你只能用instanceof进行排序——它返回true或false。使用typeof你可以得到typeof提供的东西
使用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"
所以在我看来,这取决于你在检查什么类型的数据。