在我的特殊情况下:
callback instanceof Function
or
typeof callback == "function"
这有关系吗,有什么区别?
额外的资源:
花园typeof vs instanceof
在我的特殊情况下:
callback instanceof Function
or
typeof callback == "function"
这有关系吗,有什么区别?
额外的资源:
花园typeof vs instanceof
当前回答
我建议使用原型的callback.isFunction()。
他们已经找出了其中的区别,你可以相信他们的理由。
我猜其他JS框架也有这样的东西。
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)
我认为,当callback是Function的子类型时,instanceof也可以工作
还有一种情况是你只能用instanceof进行排序——它返回true或false。使用typeof你可以得到typeof提供的东西
其他重要的实际差异:
// Boolean
var str3 = true ;
alert(str3);
alert(str3 instanceof Boolean); // false: expect true
alert(typeof str3 == "boolean" ); // true
// Number
var str4 = 100 ;
alert(str4);
alert(str4 instanceof Number); // false: expect true
alert(typeof str4 == "number" ); // true
当检查一个函数时,必须总是使用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来检查函数。