JavaScript 中原始值和对象包装值的可用性有何用处?
我不久前写了一篇博客文章,详细介绍了 JavaScript 中原始值类型和对象包装值类型的可用性(对于数字、字符串和布尔值等)会导致麻烦,包括但不限于类型转换为布尔值(例如对象包装的 NaN、“”和 false 实际上类型转换为 true)。
我的问题是,面对所有这些混乱和问题,JavaScript 为内置类提供两种类型的值有什么好处吗?
编辑:感谢您的快速解答。我认为 JavaScript 的创建者打算将包装原生作为使标量值具有子方法的一种方式,但它显然适得其反,导致更多问题。
I wrote a blog post a while ago detailing how the availability of both primitive and object-wrapped value types in JavaScript (for things such as Number, String and Boolean) causes trouble, including but not limited to type-casting to a boolean (e.g. object-wrapped NaN, "" and false actually type-cast to true).
My question is, with all this confusion and problems, is there any benefit to JavaScript having both types of values for the built-in classes?
Edit: Thanks for the quick answers. I think that the creators of JavaScript intended wrapped natives as a way to make scalar values have child methods, but it clearly backfired, causing more problems.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据 Douglas Crockford 的说法,它们从来没有用:
他甚至建议在第四版ECMAScript 规范。
According to Douglas Crockford, they are never useful:
He even recommended their deprecation for the 4th Edition of the ECMAScript specification.
JavaScript 与许多语言一样,也有好的部分和坏的部分。
这是非常非常糟糕的部分之一。
恕我直言,类型包装确实没有太多好处,只有坏处。
我们的朋友道格拉斯·克罗克福德一直在关注这个问题,事实上他从第一天起就反对这个问题。这就是您需要知道的全部。
JavaScript, like many languages, has good parts and bad parts.
This is one of the really really bad parts.
IMHO, there really isn't much benefit, only harm, from typed wrappers.
Our friend Douglas Crockford has been all over this issue, in fact he has been against it from day one. That's all you need to know.
道格拉斯·克罗克福德(Douglas Crockford)虽然是最聪明的人之一,但他不是上帝——他所说的一切都不应该盲目遵循。事实上,在一种情况下,如果您想通过引用传递值,您可能会更喜欢包装器而不是原始类型。
原始值始终按值传递,对象按引用传递。因此,如果由于某种原因您需要通过引用传递数字,那么您可以使用 Number 对象来完成。实际上,您无法在不丢失引用的情况下更改数字的值(据我所知),但您可以像任何对象一样随意添加其他参数 - 这是原始数字不支持的。
Douglas Crockford, although being one of the smartest guys out there, is not God - everything he says should not be followed blindly. In fact there is one situation where you would like to prefer wrappers against primitive types - if you would like to pass values around by reference.
Primitive values are always passed around by value and objects by reference. So if for some reason you need to pass numbers by reference then you can do it with the Number objects. You can't actually change the value of the number without loosing the reference (AFAIK) but you can add additional parameters at will as with any object - that's something primitive numbers do not support.