What is the purpose of new Boolean() in Javascript?(Javascript中new Boolean()的目的是什么?)
问题描述
有什么用:
var flag = new Boolean(false);
相比:
var flag = false;
你什么时候真正使用new Boolean
?
推荐答案
全局函数Boolean()
可以在没有new
的情况下进行类型转换,例如
The global function Boolean()
can be used for type casting when called without new
, eg
var foo = Boolean(bar); // equivalent to `var foo = !!bar`
当使用new
调用时,会额外创建一个包装对象,这意味着你可以为对象分配任意属性:
When called with new
, a wrapper object will be created additionally, which means that you can assign arbitrary properties to the object:
var foo = new Boolean(bar); // equivalent to `var foo = Object(Boolean(bar));`
foo.baz = 'quux';
alert(foo.baz);
这对于原始值是不可能的,因为原始值不能保存属性:
This is not possible with primitive values as primitives can't hold properties:
var foo = true;
foo.baz = 'quux';
alert(foo.baz); // `foo.baz` is `undefined`
将属性分配给基元不会因为自动装箱而产生错误,即
Assigning a property to a primitive doesn't produce an error because of auto-boxing, ie
foo.baz = 'quux';
将被解释为
// create and immediately discard a wrapper object:
(new Boolean(foo)).baz = 'quux';
要取回原始值,您必须调用 valueOf()
方法.如果您想实际使用包装的值,则需要这样做,因为对象在布尔上下文中总是评估为 true
- 即使包装的值是 false
.
To get the primitive value back, you'll have to invoke the valueOf()
method. This is needed if you want to actually use the wrapped value, because objects always evaluate to true
in boolean contexts - even if the wrapped value is false
.
我从未遇到过能够将属性分配给布尔值的有用应用程序,但在需要引用原始值的情况下,装箱可能很有用.
I've never come across a useful application of being able to assign properties to booleans, but boxing might be useful in cases where a reference to a primitive value is needed.
这篇关于Javascript中new Boolean()的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Javascript中new Boolean()的目的是什么?
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07