开发者

Change Truthy/Falsey value of Javascript Object

Basically can I do the following...

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

I could take advantage of the fact !,+,~... Call valueOf/toString and do the following, but I would like开发者_Go百科 to avoid that.

var obj = {valueOf:function(){return 0}}:
obj.falsey = true;
if(!!obj){
   //code not executed
}else{
   //code executed
}

Why would I want to do this? Because I'm curious :D


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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜