I want to create my own object of type Boolean. But I do not want to pollute Boolean.prototype. So I created MyBool as
MyBool = function (x) {
this.value = x;
this.valueOf = function () { return x; };
this.toString = function () { return x; };
}
MyBool.prototype.and = function (y) {
if (y.constructor !== MyBool) throw 'You cannot do that!';
return this.value && y.value;
}
and its instances
mytrue = new MyBool(true);
myfalse = new MyBool(false);
But now I noticed that
if (myfalse) {
console.log ("myfalse is true!!!")
}
prints that myfalse is true !!!
(However, + myfalse (that is, the [[ToNumber]] conversion) comes to false, thanks to valueOf)
This is obvious because only the following values are false in ECMAScript.
undefined, null, false, +0, -0, NaN, ''
If Argument Type is Object, [[ToBoolean]] returns us anyway. (see ECMA Type Conversion and Testing)
Is there any tricky way to create a falsification object? This is normal if
myfalse.constructor is MyBool
(!! myfalse) is false
Any cheat is welcome, including ECMA5 set / get / defineProperty or something else.
Thanks in advance.
source
share