为什么instanceof对某些文字返回false? [英] Why does instanceof return false for some literals?

查看:137
本文介绍了为什么instanceof对某些文字返回false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

"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?

在FF3,IE7,Opera和Chrome中也是如此。所以,至少它是一致的。

It's the same in FF3, IE7, Opera, and Chrome. So, at least it's consistent.

错过了一些。

12.21 instanceof Number //=> false
/foo/ instanceof RegExp //=> true


推荐答案

基元是一种不同于创建的对象的类型来自Javascript。来自 Mozilla API文档

Primitives are a different kind of type than objects created from within Javascript. From the Mozilla API docs:

var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral";
color2 instanceof String; // returns false (color2 is not a String object)

我找不到任何方法来构造带代码的原始类型,也许是不可能的。这可能是人们使用 typeoffoo===string而不是 instanceof 的原因。

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.

记住这样的事情的一个简单方法就是问自己我想知道什么是理智和易学?无论答案是什么,Javascript都会做另一件事。

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.

这篇关于为什么instanceof对某些文字返回false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆