I'm looking at what the Boolean object works. It can't be used as reference value transfer. Because the value can't be changed. What's the use of using the new operator? The problem can be solved by creating a new boolean object myself. But that doesn't answer the question, why doesn't there be a set function in the boolean object? Creating a boolean object means nothing to me. Because you can't do anything. Is there a solution other than creating a new object? and what does the boolean object do?
let bool=true;
let boolObj=new Boolean(true);
let ref=boolObj;
//set booObj false
console.log(ref.valueOf());//expected out:false
Is there a solution other than creating a new object?
If the problem is that you want an object with mutable boolean state, then yes, that's the solution:
const boolObj = {flag: true, valueOf() { return this.flag; }};
boolObj.flag = false;
console.log(boolObj.valueOf());
Note that that uses boolObj.flag = false;
, not boolObj = false;
. The latter would store false
in boolObj
, not modify the state of the object.
What's the use of using the new operator?
There is almost never any reason to create a Boolean
object. Boolean
objects, like all the primitive wrapper objects, are immutable. Their primary purpose is to provide a specification mechanism by which "methods" can be called on primitives:
const b = false;
console.log(b.toString()); // "false"
b
is a primitive, so how can it have a method? The answer is: It can't. But when the JavaScript engine sees b.toString
, it "promotes" the primitive to the equivalent object and then gets the method from that equivalent object. (Theoretically; obviously, engines optimize that object creation away when they can.) This doesn't mean much with the built-in methods, but you can add methods. Before ES5's strict mode, that meant that there had to be an object representation of the primitive:
Object.defineProperty(Boolean.prototype, "example", {
value() {
console.log("typeof this = " + typeof this);
return !this;
},
configurable: true,
writable: true
});
false.example();
That was necessary because before ES5's strict mode, this
always had to be of type "object"
(null
or a reference to an object), it couldn't be a primitive. As of ES5's strict mode, this
is allowed to be a primitive:
"use strict";
Object.defineProperty(Boolean.prototype, "example", {
value() {
console.log("typeof this = " + typeof this);
return !this;
},
configurable: true,
writable: true
});
false.example();
I said "almost never" above because there is one use case for Boolean
objects, but it's not a very good one: Tristate flags. You can use null
for the indeterminate state, new Boolean(true)
for the true state, and new Boolean(false)
for the false state. Again, though, it's not a great use case. :-)