Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

javascript - 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. I can't see a single use for them. What's their point? Why wouldn't you use just true and false?

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. 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. (Java works similarly, although Scala and Python largely reject this distinction).

Note that Boolean isn't the only "wrapper type". There are also String and Number, for instance.

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.

Happy coding.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...