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?
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.