问题描述
有什么用:
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()的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!