在我的特殊情况下:

callback instanceof Function

or

typeof callback == "function"

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

额外的资源:

花园typeof vs instanceof


当前回答

使用instanceof自定义类型:

var ClassFirst = function () {};
var ClassSecond = function () {};
var instance = new ClassFirst();
typeof instance; // object
typeof instance == 'ClassFirst'; // false
instance instanceof Object; // true
instance instanceof ClassFirst; // true
instance instanceof ClassSecond; // false 

对于简单的内置类型使用typeof:

'example string' instanceof String; // false
typeof 'example string' == 'string'; // true

'example string' instanceof Object; // false
typeof 'example string' == 'object'; // false

true instanceof Boolean; // false
typeof true == 'boolean'; // true

99.99 instanceof Number; // false
typeof 99.99 == 'number'; // true

function() {} instanceof Function; // true
typeof function() {} == 'function'; // true

对于复杂的内置类型使用instanceof:

/regularexpression/ instanceof RegExp; // true
typeof /regularexpression/; // object

[] instanceof Array; // true
typeof []; //object

{} instanceof Object; // true
typeof {}; // object

最后一个有点棘手:

typeof null; // object

其他回答

当检查一个函数时,必须总是使用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来检查函数。

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

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

尽管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

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