我正在阅读关于JavaScript的Mozilla手册,我在阅读时谈到了这一点,布尔对象。我看不到他们的一个用途。他们有什么意义?为什么不使用 true 和 false ?
<顺便说一句,我根本不懂Java,我不怕学习新东西,因此我为什么要学习JavaScript。我是一名PHP程序员,后端人员,我想学习如何做一些前端工作,所以我正在阅读 Mozilla JavaScript指南。解决方案因为这是(有点可悲的是)语言是如何定义的 - 我怀疑它最初用于性能/优化;请注意分配给下面的字符串属性的情况。 (Java的工作方式类似,尽管Scala和Python在很大程度上拒绝这种区别)。
注意 Boolean 不是只有包装类型。例如,还有 String 和 Number 。
因此存在许多怪癖(下面可能同样适用于布尔值):
typeof(foo )// string typeof(new String(foo))// object fooinstanceof String // false new String(foo)instanceof String // true //结果是未定义的:一个字符串是一个原始的,并且默默地吃了赋值 //这也使它成为一个更便宜的值,因为它不是一个真正的对象x =f; x.bar = 42; x.bar //结果是42:String是一个具有真实属性的真实对象! //然而,这也意味着它可能有更多的开销 x = new String(f); x.bar = 42; x.bar我知道这并没有回答这个问题,而是更多地扔掉了一些木头在火上; - )
上面唯一真正的问题可能是 new Boolean(false)是一个真值y。
快乐编码。
I am reading through the Mozilla Manual on JavaScript, and I come to this point in my reading, Boolean object. I can't see a single use for them. What's their point? Why wouldn't you use just true and false?
By the way, I don't know Java at all and I'm not afraid of learning new things that consequently why I'm trying to learn JavaScript. I'm a PHP programmer, a back end guy, and I'd like to learn how to do some front end work, so I'm reading the Mozilla JavaScript Guide.
解决方案Because this is (somewhat sadly) how the language was defined -- I suspect it was originally for performance/optimization; note the case of assignment to a string property below. (Java works similarly, although Scala and Python largely reject this distinction).
Note that Boolean isn't the only "wrapper type". There are also String and Number, for instance.
Because of this there remains a number of quirks (the below could just as much apply to Boolean):
typeof("foo") // string typeof(new String("foo")) // object "foo" instanceof String // false new String("foo") instanceof String // true // result is undefined: a string is a primitive and silently "ate" the assignment // this also makes it a much cheaper value as it's not a "real" object x = "f"; x.bar = 42; x.bar // result is 42: a String is a "real" object with real properties! // however, this also means that it may have a good bit more overhead x = new String("f"); x.bar = 42; x.barI know this didn't "answer" the question, but rather chucks some more wood on the fire ;-)
The only real "gotcha" otherwise from the above is that perhaps new Boolean(false) is a truth-y value.
Happy coding.
更多推荐
布尔对象有什么意义?
发布评论