在我的特殊情况下:

callback instanceof Function

or

typeof callback == "function"

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

额外的资源:

花园typeof vs instanceof


当前回答

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

callback instanceof Function

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

其他回答

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

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快

显著的实际差异:

var str = 'hello word';

str instanceof String   // false

typeof str === 'string' // true

别问我为什么。

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)

使用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

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