I have a custom Javascript class (created using John Resig's Simple Javascript Inheritance). I want to be able to compare two instances of this class, using the ==
, <
, >
, >=
, and <=
symbols.
How do I override the comparators of my custom class?
The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.
In JavaScript, there are two types of comparison operators: Type-converting (or Abstract) Strict.
Try overriding valueOf(). Then you can write stuff like this:
if (obj1.valueOf() === obj2.valueOf())
if (obj1.valueOf() < obj2.valueOf())
if (obj1.valueOf() > obj2.valueOf())
So whenever I need a special JavaScript object type to override the comparison I just add valueOf to the prototype. It works great for primitive types as well since valueOf just returns the value.
Just watch out for nulls.
Lee is correct, if you implement valueOf then when comparing objects (not with === or !===) this will be used but you'll have to use toString as well because it's used when sorting arrays for some reason.
function Test(value){
this.value=value;
}
Test.prototype.toString=function(){
console.log("tostring called");
// could do something with case sensitiveness here
return new String(this.valueOf());
}
Test.prototype.valueOf=function(){
console.log("valueof called");
return this.value;
}
var t1=new Test(11);
var t2=new Test(1.1);
var arr=[t1,t2];
console.log('sorted',arr.sort().map(o=>o.value));
console.log('larger',t1>=t2);
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