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?
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.
Try overriding valueOf(). Then you can write stuff like this:
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.
this cannot be done in the way that you are implying it should be done (though that would be sweet). The best way I have seen this done is to implement on the prototype a set of methods to act like comparatives:
I was thinking about this problem somemore at work today and there is an alternate way to take advantage of the standard comparison operators but have custom object comparisons. The trick would be to have a property (getter) on the object that represented the comparable state. This would require that all instances of the object evaluate to the same numeric value given the same comparable properties. As an example let's talk vectors:
then when you set up vectors:
This only works of course if you are dealing with objects that can be broken down into simple numeric expression of value, but the upside is that the implementation code to get the basic effect is pretty low and you could even go so far as to make the object itself a function that returns the numeric expression of it's component parts.
now you have all the benefits of the object with easy numeric comparisons and it's even kinda terse.