Extending the Boolean Object in Javascript with an 'invert' function
I would like to extend the Boolean object with a prototype function that inverts it's current value. Until now, I've been doing something like this:
var bool = true;
bool = !bool;
console.log(bool); // false
My attempt开发者_如何学JAVAs at extending the Boolean object were not fruitful. That's 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 along these lines:
var bool = true;
bool.invert();
console.log(bool); // false
Yes, I know, extending build-in Object is commonly considered a bad idea. Please let's save that discussion for another day.
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 this is not so smart, you can store the boolean-value in one object and pass this object as reference
精彩评论