How can we create a Boolean-like object in JavaScript?

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.

+3
source share
3 answers

, , :

var myBool = new Boolean(false);
if (myBool) {
    alert('Not false');
}
+1

, , . ?

var someBoolean = false,
    someObj = { };

if (someBoolean === false)
{
    // tada, someBoolean is a boolean AND false
}

// Returns false because someObj is NOT a boolean
if (someObj === true)
{
   ..
}
0

Understand what you are doing if(myfalse){}. He tests existence myfalse, not its truth or falsehood. In this case, it myfalseis an object and, therefore, exists and, therefore, has the value true.

-1
source

All Articles