在我的特殊情况下:

callback instanceof Function

or

typeof callback == "function"

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

额外的资源:

花园typeof vs instanceof


当前回答

根据MDN关于typeof的文档,用"new"关键字实例化的对象类型为'object':

typeof 'bla' === 'string';

// The following are confusing, dangerous, and wasteful. Avoid them.
typeof new Boolean(true) === 'object'; 
typeof new Number(1) === 'object'; 
typeof new String('abc') === 'object';

而关于instanceof点的文档说明:

const objectString = new String('String created with constructor');
objectString instanceOf String; // returns true
objectString instanceOf Object; // returns true

因此,如果有人想检查,例如,某东西是一个字符串,无论它是如何创建的,最安全的方法是使用instanceof。

其他回答

我从小接受严格的面向对象教育

callback instanceof Function

字符串容易出现我糟糕的拼写或其他拼写错误。而且我觉得读起来更好。

性能

在两者都适用的情况下,Typeof比instanceof更快。

根据您的引擎,有利于typeof的性能差异可能在20%左右。(您的里程可能有所不同)

下面是Array的基准测试:

var subject = new Array();
var iterations = 10000000;

var goBenchmark = function(callback, iterations) {
    var start = Date.now();
    for (i=0; i < iterations; i++) { var foo = callback(); }
    var end = Date.now();
    var seconds = parseFloat((end-start)/1000).toFixed(2);
    console.log(callback.name+" took: "+ seconds +" seconds.");
    return seconds;
}

// Testing instanceof
var iot = goBenchmark(function instanceofTest(){
     (subject instanceof Array);
}, iterations);

// Testing typeof
var tot = goBenchmark(function typeofTest(){
     (typeof subject == "object");
}, iterations);

var r = new Array(iot,tot).sort();
console.log("Performance ratio is: "+ parseFloat(r[1]/r[0]).toFixed(3));

结果

instanceofTest took: 9.98 seconds.
typeofTest took: 8.33 seconds.
Performance ratio is: 1.198

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

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

两者在功能上相似,因为它们都返回类型信息,但我个人更喜欢instanceof,因为它比较的是实际类型而不是字符串。类型比较不容易出现人为错误,而且技术上更快,因为它比较内存中的指针,而不是整个字符串的比较。