Change Truthy / Falsey value of a Javascript object

Basically, I can do the following ...

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

I could use the fact ! , + , ~ ... Call valueOf/toString and follow these steps, but I would like to avoid this.

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

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

+4
source share
3 answers

You can take a false Number , Boolean .... from the 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); 

It does, but obviously it pollutes Number.prototype, so you really have to take another Number object from another iframe.

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

Ultimately, just not a good idea.

0
source

No, you can’t. You must implement some custom logic.

+2
source

You can use the free equal to compare it with a logical one. People do this all the time, and finally, it serves a specific purpose.

 var obj = {valueOf: function() {return !this.falsey;}}; obj.falsey = true; if (obj == true) { //code not executed } else if (obj == false) { //code executed } 
-1
source

All Articles