在我的特殊情况下:

callback instanceof Function

or

typeof callback == "function"

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

额外的资源:

花园typeof vs instanceof


当前回答

没有必要用上面的大量例子来压倒你,只需要记住两个观点:

typeof var; is an unary operator will return the original type or root type of var. so that it will return primitive types(string, number, bigint, boolean, undefined, and symbol) or object type. in case of higher-level object, like built-in objects (String, Number, Boolean, Array..) or complex or custom objects, all of them is object root type, but instance type built base on them is vary(like OOP class inheritance concept), here a instanceof A - a binary operator - will help you, it will go through the prototype chain to check whether constructor of the right operand(A) appears or not.

所以当你想检查“根类型”或使用基元变量时,使用“typeof”,否则使用“instanceof”。

Null是一种特殊情况,它看起来很原始,但实际上是object的特殊情况。使用a === null代替检查null。

另一方面,function也是一种特殊情况,它是内置对象,但typeof返回函数

正如你所看到的,instanceof必须遍历原型链,而typeof只检查根类型一次,所以很容易理解为什么typeof比instanceof快

其他回答

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

我在Safari 5和Internet Explorer 9中发现了一些非常有趣的(读作“可怕的”)行为。我在Chrome和Firefox中成功地使用了这个功能。

if (typeof this === 'string') {
    doStuffWith(this);
}

然后我在IE9中测试,它根本不能工作。大惊喜。但在Safari中,它是间歇性的!我开始调试,发现ie总是返回false。但最奇怪的是,Safari似乎在它的JavaScript VM中做了某种优化,第一次为真,但每次点击重载时为假!

我的大脑几乎爆炸了。

所以现在我决定这样做:

if (this instanceof String || typeof this === 'string')
    doStuffWith(this.toString());
}

现在一切都很好。请注意,你可以调用"a string". tostring(),它只是返回字符串的副本,即。

"a string".toString() === new String("a string").toString(); // true

所以从现在开始我将两者都用。

var newObj = new Object;//对象实例 var newProp = "I'm xgqfrms!"/ /定义属性 var newFunc = function(name){//定义函数 Var hello ="hello, "+ name +"!"; 返回你好; } //添加属性newObj.info = newProp newObj。//添加函数 console.log(newObj.info) //我是xgqfrms! console.log(newObj.func("ET")) //你好,ET! console.log(newObj instanceof Object); / /正确的 console.log (typeof (newObj)); / /“对象”

性能

在两者都适用的情况下,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

显著的实际差异:

var str = 'hello word';

str instanceof String   // false

typeof str === 'string' // true

别问我为什么。