Reputation: 35311
Is there a way in JavaScript to pre-specify the boolean value that an arbitrary object should have?
For example, suppose I define
function NIL () {
this.car = this.cdr = this;
}
var nil = new NIL;
I would like to have !nil
evaluate to true
. Is this possible in JS?
(P.S.: I'd hoped that defining a method like toBoolean
, by analogy with toString
, would do the trick, but this did not work.)
Upvotes: 2
Views: 81
Reputation: 39777
You can make it work - sort of, by overriding "valueOf":
NIL.prototype.valueOf = function () {
return false;
};
It won't make !nil == true
but it will make nil == false
.
But since this behavior is inconsistent, I agree with other answers - you should use your own functions.
Upvotes: 1
Reputation: 1656
The rules for conversion to boolean are fixed by the ECMAscript Language Specification, so you cannot do that. You should use your own functions to perform your checks.
Upvotes: 2
Reputation: 54514
It seems you want to use functional programming way to define a customize typing system. I am not sure whether this is what you need, but you this does what you described
function NIL () {
this.car = this.cdr = this;
this.isNull = function(){
return false;
}
}
var nil = new NIL();
console.log(!nil.isNull()) // true
Upvotes: 0