Javascript中new Boolean()的目的是什么?

编程入门 行业动态 更新时间:2024-10-26 20:35:48
本文介绍了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()的目的是什么?

本文发布于:2023-11-09 10:33:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572151.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:目的   Javascript   Boolean

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!