简体   繁体   English

布尔对象有什么意义?

[英]What's the point of the Boolean object?

I am reading through the Mozilla Manual on JavaScript, and I come to this point in my reading, Boolean object . 我正在阅读关于JavaScript的Mozilla手册,我在阅读布尔对象时谈到了这一点。 I can't see a single use for them. 我看不到他们的一个用途。 What's their point? 他们有什么意义? Why wouldn't you use just true and false ? 你为什么不使用只是truefalse

By the way, I don't know Java at all and I'm not afraid of learning new things that consequently why I'm trying to learn JavaScript. 顺便说一句,我根本不懂Java,我不怕学习新东西,因此我为什么要学习JavaScript。 I'm a PHP programmer, a back end guy, and I'd like to learn how to do some front end work, so I'm reading the Mozilla JavaScript Guide . 我是一名PHP程序员,后端人员,我想学习如何做一些前端工作,所以我正在阅读Mozilla JavaScript指南

Because this is (somewhat sadly) how the language was defined -- I suspect it was originally for performance/optimization; 因为(有点可悲)这是如何定义语言的 - 我怀疑它最初是为了性能/优化; note the case of assignment to a string property below. 注意分配给下面的string属性的情况。 (Java works similarly, although Scala and Python largely reject this distinction). (Java的工作方式类似,尽管Scala和Python在很大程度上拒绝了这种区别)。

Note that Boolean isn't the only "wrapper type". 请注意, Boolean不是唯一的“包装器类型”。 There are also String and Number , for instance. 例如,还有StringNumber

Because of this there remains a number of quirks (the below could just as much apply to Boolean): 因此,仍存在许多怪癖(下面的内容可能同样适用于布尔值):

typeof("foo") // string
typeof(new String("foo")) // object
"foo" instanceof String // false
new String("foo") instanceof String // true

// result is undefined: a string is a primitive and silently "ate" the assignment
// this also makes it a much cheaper value as it's not a "real" object
x = "f"; x.bar = 42; x.bar

// result is 42: a String is a "real" object with real properties!
// however, this also means that it may have a good bit more overhead
x = new String("f"); x.bar = 42; x.bar

I know this didn't "answer" the question, but rather chucks some more wood on the fire ;-) 我知道这并没有“回答”这个问题,而是在火上扔了一些木头;-)

The only real "gotcha" otherwise from the above is that perhaps new Boolean(false) is a truth-y value. 从上面来看唯一真正的“问题”是,也许new Boolean(false)是一个真值y值。

Happy coding. 快乐的编码。

JavaScript language design has quite many dusty corners, and the Boolean is one of them; JavaScript语言设计有很多尘埃落定的角落,布尔就是其中之一; it is not used in practice. 它没有在实践中使用。

This: 这个:

var a = [];
alert(a instanceof Array);

will tell you "true". 会告诉你“真实”。 But this: 但是这个:

var b = true;
alert(b instanceof Boolean);

for some reason will show "false". 由于某种原因将显示“虚假”。

In short: forget about it. 简而言之:忘了它。

Creating a new boolean object "basically" runs the bit of code in the statement and then from there returns the true boolean value. 创建一个新的布尔对象“基本上”运行语句中的一些代码,然后从那里返回真正的布尔值。

From the same docs: 来自相同的文档:

1 var b = new Boolean(false);
2 if (b) // this condition evaluates to true

https://developer.mozilla.org/en/JavaScript/Guide/Statements#if...else_Statement https://developer.mozilla.org/en/JavaScript/Guide/Statements#if...else_Statement

Perhaps because JavaScript objects are extensible in ways that primitives aren't? 也许是因为JavaScript对象可以以原语不可扩展的方式进行扩展? (I'm just guessing here, I've never had a need for Boolean. (我只是在这里猜测,我从来不需要布尔值。

Boolean.prototype.bang = function() {
    return !this.valueOf();
}

true.bang(); // false

Everything in JavaScript is an object. JavaScript中的所有内容都是一个对象。 But at the same time we also have primitives. 但与此同时我们也有原始人。 It's really confusing, just don't overthink it. 这真的令人困惑,只是不要过度思考它。

From the documentation: 从文档:

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. 不要将原始布尔值true和false与Boolean对象的true和false值混淆。 Any object whose value is not undefined , null, 0, NaN, or the empty string , including a Boolean object whose value is false, evaluates to true when passed to a conditional statement. 任何值未定义的对象,null,0,NaN或空字符串(包括值为false的Boolean对象)在传递给条件语句时计算结果为true。

Imagine the following scenario: 想象一下以下场景:

if(SomeBoolean){...}

will be true in scenarios where SomeBoolean is a Boolean object. SomeBoolean是布尔对象的情况下会出现这种情况。

Conversely: 反过来:

if(false){...}

will always be false 永远都是假的

Addendum for clarification. 补遗澄清。

var someString = new Boolean("MyNonEmptyString")
if(someString) //true
var otherString = new Boolean("")
if(otherString) //false

你可以使用return Boolean(something)从任何值强制转换为true或false,但是写入return !!something更短的return !!something ,这也会强制成为真或假。

I would have to side with most of the people here that there isn't much need for the Boolean object, but I do want to point out a couple of things. 我不得不支持这里的大多数人对布尔对象不太需要,但我想指出一些事情。

An explicit comparison will still evaluate like a boolean: 显式比较仍将像布尔值一样进行评估:

var someBool = new Boolean(false);
if (someBool == false)
    alert('Got here'); //Alerts 'Got here'

Because of this, you could sort of extend it to a subclass and still be able to have the comparison work as above: 正因为如此,你可以排序的将其扩展到一个子类,并仍然能够具有上述的比较工作:

var classExtension = {
    toYN: function() {
        return this == false ? 'N' : 'Y';
    }
};

function getNewClass(val) {
    var newBool = new Boolean(val);
    jQuery.extend(newBool, classExtension);
    return newBool;
}

var newTest = getNewClass(false);
if (newTest)
    alert('It\'s alive');
if (newTest == false)
    alert('And still a bool');
alert(newTest.toYN());

This will alert 'It's alive', 'And still a bool' and 'N'. 这将警告'它还活着','仍然是一个布尔'和'N'。 http://jsfiddle.net/fkJuk/ http://jsfiddle.net/fkJuk/

But again, would you ever really need this? 但是,你真的需要这个吗? Even if you did, it would probably be better just to have your own separate class with a boolean property that gets checked. 即使你这样做,也可能更好的方法是让你自己的单独类具有一个被检查的布尔属性。 In the end, it's probably here for consistency; 最后,这可能是为了保持一致性; every primitive has direct constructor and prototype access in JavaScript. 每个原语都有JavaScript中的直接构造函数和原型访问。

Going back to the specification (ECMA-262.pdf page 151), note that when Boolean is called as a function rather than as a constructor, it does type conversion. 回到规范(ECMA-262.pdf第151页),请注意当布尔值作为函数而不是构造函数调用时,它会进行类型转换。 Thus: 从而:

var t = 5
  , f = 0

console.log(Boolean(t))  //Prints true
console.log(Boolean(f))  //Prints false

Of course, being a JavaScript object, you can use it as a prototype using the 'new' operator, as others have noted, but I don't see any reason for doing that. 当然,作为一个JavaScript对象,您可以使用'new'运算符将其用作原型,正如其他人所指出的那样,但我认为没有任何理由这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM