【问题标题】:Differences between typeof and instanceof in JavaScript [duplicate]JavaScript中typeof和instanceof之间的区别[重复]
【发布时间】:2013-01-28 04:17:33
【问题描述】:

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

我一直注意到 typeof 和 instanceof 之间存在一些奇怪的差异,但这里有一个让我很困扰:

var foo = 'foo';
console.log(typeof foo);

Output: "string"

console.log(foo instanceof String);

Output: false

那里发生了什么?

【问题讨论】:

标签: javascript node.js syntax instanceof typeof


【解决方案1】:

typeof 是一个“返回”你传递给它的原始类型的构造。
instanceof 测试右操作数是否出现在左原型链中的任何位置。

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

【讨论】:

  • 这个“巨大”的区别在哪里?在当前的 NodeJS 中,如果我使用x = 'x'; y = new String('x'),我可以将xy 处理几乎可以互换,除了少数几个运算符,如typeofinstanceof===y.constructor === x.constructor 甚至返回 true!
【解决方案2】:

有文字字符串和String 类。它们是独立的,但它们可以无缝地工作,即您仍然可以将 String 方法应用于文字字符串,并且它的行为就像文字字符串是 String 对象实例一样。

如果你显式创建了一个String 实例,它就是一个对象,它是String 类的一个实例:

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

输出:

object
true

【讨论】:

  • 您应该注意typeof 输出实际上是"object"(小写字符串)
  • @rgthree:是的,你是对的。我更正了输出。
  • @rgthree 这也应该添加到回答中
猜你喜欢
  • 1970-01-01
  • 2010-10-06
  • 2015-09-03
  • 2017-04-11
  • 2011-02-25
  • 2017-06-25
  • 2017-03-24
  • 2016-09-04
相关资源
最近更新 更多