Change Truthy/Falsey value of Javascript Object

后端 未结 3 927
情歌与酒
情歌与酒 2020-12-21 04:10

Basically can I do the following...

var obj = {}:
obj.falsey = true;
if(obj){
   //code not executed
}else{
   //code executed
}

I could ta

相关标签:
3条回答
  • 2020-12-21 04:25

    You can use loose equal to compare it to a boolean. People do that all the time, and finally it serves some purpose.

    var obj = {valueOf: function() {return !this.falsey;}};
    obj.falsey = true;
    if (obj == true) {
       //code not executed
    } else if (obj == false) {
       //code executed
    }
    
    0 讨论(0)
  • 2020-12-21 04:27

    No, you can't. You have to implement some custom logic.

    0 讨论(0)
  • 2020-12-21 04:42

    You can borrow a false Number,Boolean.... from an iframe and extend its prototype.

    Basically the following doesn't work because Numbers are a primitive value.

    var x = 0;
    x.test = 'yo';
    console.log(x.test);
    

    This does, but obviously this pollutes the Number.prototype, so you should really borrow a different Number object from another iframe.

    var x = 0;
    Number.prototype.test = 'yo';
    console.log(x.test);
    

    Ultimately, just not a very good idea.

    0 讨论(0)
提交回复
热议问题