Can an Object be false?

前端 未结 9 1594
温柔的废话
温柔的废话 2020-12-06 04:35

Is there any way to make an object return false in javascript?

var obj = new Object();

console.log(!!obj) // prints \"true\" even if it\'s empty
         


        
9条回答
  •  情歌与酒
    2020-12-06 05:00

    We can overwrite Object.prototype.valueOf to make an object appear to be false when it is coerced into a primitive, for example during ==.

    However it will not appear to be false when we force it into a boolean using !!, so it doesn't really work in the general case.

    var obj = {
        valueOf: function () {
            return false
        }
    }
    
    > obj == false
    true               // Good, we fooled them!
    
    > !!obj
    true               // Not so good, we wanted false here
    
    > Boolean(obj)
    true               // Not so good, we wanted false here
    

提交回复
热议问题