JavaScript 中 typeof 和 instanceof 的区别 [英] Differences between typeof and instanceof in JavaScript
问题描述
我正在使用 node.js,所以这可能特定于 V8.
I'm working with node.js, so this could be specific to V8.
我一直注意到 typeof 和 instanceof 之间存在一些奇怪的差异,但这里有一个让我很烦恼的地方:
I've always noticed some weirdness with differences between typeof and instanceof, but here is one that really bugs me:
var foo = 'foo';
console.log(typeof foo);
Output: "string"
console.log(foo instanceof String);
Output: false
那里发生了什么?
推荐答案
typeof
是一种返回"传递给它的任何原始类型的结构.instanceof
测试右侧操作数是否出现在左侧原型链中的任何位置.
typeof
is a construct that "returns" the primitive type of whatever you pass it.
instanceof
tests to see if the right operand appears anywhere in the prototype chain of the left.
需要注意的是,字符串字面量 "abc"
和字符串对象 new String("abc")
之间存在巨大差异.在后一种情况下,typeof
将返回object"而不是string".
It is important to note that there is a huge difference between the string literal "abc"
, and the string object new String("abc")
. In the latter case, typeof
will return "object" instead of "string".
这篇关于JavaScript 中 typeof 和 instanceof 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!