I'm guessing this is probably application specific however I am using node.js - as long as it works in the v8 engine, I don't mind.
I'm trying to create an Object
that evaluates to false, for example:
var Foo = function() { return this; }
var bar = new Foo;
if (bar) // returns false;
Is this possible by overriding a certain function of the object, e.g. toString
?
In case anyone is wondering what use case this may have: it is for returning error objects from functions that normally return a boolean value, but could also possibly have encountered an error and returned my custom error object.
I want any following conditionals to act as if the function returned a false value without having to modify the conditionals to accommodate for the possibility of a non boolean value.
The closest you can get is like
if (+obj)
Where a falsy object defines a .valueOf()
function that returns 0
or false
:
var o = {
valueOf: function() {
return false;
}
};
if (+o) {
throw unreachable();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With