JavaScript中typeof和instanceof的区别

我正在使用node.js,所以这可能是特定于V8的。

我一直注意到typeof和instanceof之间的差异,但是这里有一个真正让我感到困惑的东西:

var foo = 'foo'; console.log(typeof foo); Output: "string" console.log(foo instanceof String); Output: false 

那里发生了什么?

typeof是一个构造,它可以“返回”你传递它的任何原始types。
instanceoftesting,看看右边的操作数是否出现在左边的原型链的任何地方。

需要注意的是,string字面值"abc"与string对象new String("abc")之间存在巨大差异。 在后一种情况下, typeof将返回“object”而不是“string”。

有字面的string,并有String类。 它们是分开的,但是它们可以无缝地工作,也就是说,您仍然可以将String方法应用于文字string,并且它的作用就好像文字string是一个String对象实例。

如果你明确地创build了一个String实例,那它就是一个对象,它是String类的一个实例:

 var s = new String("asdf"); console.log(typeof s); console.log(s instanceof String); 

输出:

 object true