Skip to content Skip to sidebar Skip to footer

How Can We Create Boolean-like Object In Javascript?

I want to create my Boolean-like object. But I don't want to pollute Boolean.prototype. So I created MyBool like MyBool = function (x) { this.value = x; this.valueOf = function

Solution 1:

I don't think this is currently possible, if you consider:

var myBool = newBoolean(false);
if (myBool) {
    alert('Not false');
}

Solution 2:

In response to your comment, indicating you want a strict boolean. Why not use the equality operator?

var someBoolean = false,
    someObj = { };

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

// Returns false because someObj is NOT a booleanif (someObj === true)
{
   ..
}

Solution 3:

Understand what if(myfalse){} is doing. It is checking for the existence of myfalse, not whether its true or false. In this case, myfalse is an object and thus exists, and thus is true.

Post a Comment for "How Can We Create Boolean-like Object In Javascript?"