在我的特殊情况下:

callback instanceof Function

or

typeof callback == "function"

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

额外的资源:

花园typeof vs instanceof


当前回答

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

其他回答

我在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

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

根据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。

显著的实际差异:

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)

使用typeof的一个很好的理由是变量可能是未定义的。

alert(typeof undefinedVariable); // alerts the string "undefined"
alert(undefinedVariable instanceof Object); // throws an exception

使用instanceof的一个很好的理由是变量可能为空。

var myNullVar = null;
alert(typeof myNullVar ); // alerts the string "object"
alert(myNullVar  instanceof Object); // alerts "false"

所以在我看来,这取决于你在检查什么类型的数据。