JavaScript 中 typeof 和 instanceof 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14839656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:06:19  来源:igfitidea点击:

Differences between typeof and instanceof in JavaScript

javascriptnode.jssyntaxinstanceoftypeof

提问by Eric

I'm working with node.js, so this could be specific to V8.

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

I've always noticed some weirdness with differences between typeof and instanceof, but here is one that really bugs me:

我一直注意到 typeof 和 instanceof 之间存在一些奇怪的差异,但这里有一个真正让我烦恼的地方:

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

Output: "string"

console.log(foo instanceof String);

Output: false

What's going on there?

那里发生什么事了?

回答by Niet the Dark Absol

typeofis a construct that "returns" the primitive type of whatever you pass it.
instanceoftests to see if the right operand appears anywhere in the prototype chain of the left.

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

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, typeofwill return "object" instead of "string".

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

回答by Guffa

There is literal strings and there is the Stringclass. They are separate, but they work seamlessly, i.e. you can still apply Stringmethods to a literal string, and it will act as if the literal string was a Stringobject instance.

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

If you explicitly create a Stringinstance, it's an object, and it's an instance of the Stringclass:

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

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

Output:

输出:

object
true