在Javascript的目的是什么

在Javascript的目的是什么

本文介绍了什么是新的布尔()在Javascript的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么用的:

var flag = new Boolean(false);

相比于

var flag = false;

你什么时候实际使用新布尔

推荐答案

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

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.

这篇关于什么是新的布尔()在Javascript的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 13:09