且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是新的布尔()在Javascript的目的是什么?

更新时间:2022-06-12 04:31:37

全局函数布尔()当没有,例如:

The global function Boolean() can be used for type casting when called without new, eg

var foo = Boolean(bar); // equivalent to `var foo = !!bar`

在一个名为,一个包装对象会被另外创建,这意味着你可以指定任意属性的对象:

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';

将作为PTED

will be interpreted as

// create and immediately discard a wrapper object:
(new Boolean(foo)).baz = 'quux';

要获得原始值回来了,你就必须调用的valueOf()方法。如果您确实希望使用包装的价值这是必要的,因为对象总是为真正在布尔环境 - 即使包裹值为

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.