What#39;s the point of the Boolean object?(布尔对象的意义何在?)
问题描述
我正在阅读关于 JavaScript 的 Mozilla 手册,我在阅读中来到了这一点,布尔对象.我看不到它们的单一用途.他们的意义何在?为什么不只使用 true 和 false?
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?
顺便说一句,我根本不懂 Java,而且我不害怕学习新事物,这也是我尝试学习 JavaScript 的原因.我是一名 PHP 程序员,一名后端人员,我想学习如何做一些前端工作,所以我正在阅读 Mozilla JavaScript 指南.
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.
推荐答案
因为这是(有点遗憾)语言的定义方式——我怀疑它最初是为了性能/优化;请注意下面分配给 string 属性的情况.(Java 的工作方式类似,尽管 Scala 和 Python 在很大程度上拒绝这种区别).
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).
请注意,Boolean 并不是唯一的包装器类型".例如,还有 String 和 Number.
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.bar
我知道这并没有回答"这个问题,而是在火上扔了一些木头;-)
I know this didn't "answer" the question, but rather chucks some more wood on the fire ;-)
上述唯一真正的陷阱"可能是 new Boolean(false) 是一个真值.
The only real "gotcha" otherwise from the above is that perhaps new Boolean(false) is a truth-y value.
编码愉快.
这篇关于布尔对象的意义何在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:布尔对象的意义何在?
基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
