What's the point of the Boolean object?

前端 未结 9 1059
遥遥无期
遥遥无期 2020-12-09 15:28

I am reading through the Mozilla Manual on JavaScript, and I come to this point in my reading, Boolean object. I can\'t see a single use for them. What\'s their point? Why w

9条回答
  •  庸人自扰
    2020-12-09 15:52

    I would have to side with most of the people here that there isn't much need for the Boolean object, but I do want to point out a couple of things.

    An explicit comparison will still evaluate like a boolean:

    var someBool = new Boolean(false);
    if (someBool == false)
        alert('Got here'); //Alerts 'Got here'
    

    Because of this, you could sort of extend it to a subclass and still be able to have the comparison work as above:

    var classExtension = {
        toYN: function() {
            return this == false ? 'N' : 'Y';
        }
    };
    
    function getNewClass(val) {
        var newBool = new Boolean(val);
        jQuery.extend(newBool, classExtension);
        return newBool;
    }
    
    var newTest = getNewClass(false);
    if (newTest)
        alert('It\'s alive');
    if (newTest == false)
        alert('And still a bool');
    alert(newTest.toYN());
    

    This will alert 'It's alive', 'And still a bool' and 'N'. http://jsfiddle.net/fkJuk/

    But again, would you ever really need this? Even if you did, it would probably be better just to have your own separate class with a boolean property that gets checked. In the end, it's probably here for consistency; every primitive has direct constructor and prototype access in JavaScript.

提交回复
热议问题