Extending Boolean Object in Javascript with Invert Feature

I would like to extend the Boolean object with a prototype that inverts the current value. So far I have been doing something like this:

var bool = true; bool = !bool; console.log(bool); // false 

My attempts to expand the Boolean object were not fruitful. This is how far I got:

 Boolean.prototype.invert = function() { return !this.valueOf(); } var bool = true; bool = bool.invert(); console.log(bool); // false 

Close, but not close enough. I am looking for a solution on these lines:

 var bool = true; bool.invert(); console.log(bool); // false 

Yes, I know, extending an inline object is usually considered bad. Please keep this discussion for another day.

+4
source share
1 answer

Scalar values ​​are immutable in all oop languages, you need a new class

 var BooleanBuilder = function( data ){ this._data = !!data; }; BooleanBuilder.prototype.valueOf = function() { return this._data; }; BooleanBuilder.prototype.invert = function() { this._data = !this._data; }; var bool = new BooleanBuilder(true); alert(bool.valueOf()); bool.invert(); alert(bool.valueOf()); // false 

but it’s not so smart, you can store a boolean in one object and pass that object as a reference

+4
source

All Articles