Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

javascript - 为什么instanceof对某些文字返回false?(Why does instanceof return false for some literals?)

"foo" instanceof String //=> false
"foo" instanceof Object //=> false
true instanceof Boolean //=> false
true instanceof Object //=> false
false instanceof Boolean //=> false
false instanceof Object //=> false

// the tests against Object really don't make sense

Array literals and Object literals match...(数组文字和对象文字匹配...)

[0,1] instanceof Array //=> true
{0:1} instanceof Object //=> true

Why don't all of them?(为什么不是所有人?)

Or, why don't they all not ?(或者,为什么不是所有人都不呢?)
And, what are they an instance of, then?(而且,它们是什么实例呢?)

It's the same in FF3, IE7, Opera, and Chrome.(在FF3,IE7,Opera和Chrome中相同。)

So, at least it's consistent.(因此,至少是一致的。)

Missed a few.(错过了几个。)

12.21 instanceof Number //=> false
/foo/ instanceof RegExp //=> true
  ask by Jonathan Lonowski translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Primitives are a different kind of type than objects created from within Javascript.(与从Javascript内部创建的对象相比,基元是另一种类型。)

From the Mozilla API docs :(从Mozilla API文档 :)
var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral";
color2 instanceof String; // returns false (color2 is not a String object)

I can't find any way to construct primitive types with code, perhaps it's not possible.(我找不到用代码构造基本类型的任何方法,也许这是不可能的。)

This is probably why people use typeof "foo" === "string" instead of instanceof .(这可能就是为什么人们使用typeof "foo" === "string"而不是instanceof 。)

An easy way to remember things like this is asking yourself "I wonder what would be sane and easy to learn"?(记住这样的事情的一种简单方法是问自己:“我想知道什么是理智且易于学习的”吗?)

Whatever the answer is, Javascript does the other thing.(无论答案是什么,JavaScript都会做其他事情。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...