class - Override default behavior of comparison operators in JavaScript -
i have custom javascript class (created using john resig's simple javascript inheritance). want able compare 2 instances of class, using ==, <, >, >=, , <= symbols.
how override comparators of custom class?
this cannot done in way implying should done (though sweet). best way have seen done implement on prototype set of methods act comparatives:
gte : function( obj ){ // greater or equal // return custom comparison object comparable on left }, gt : function( obj ){...}, // greater not equal eq : function( obj ){...}, // equal // etc. i thinking problem somemore @ work today , there alternate way take advantage of standard comparison operators have custom object comparisons. trick have property (getter) on object represented comparable state. require instances of object evaluate same numeric value given same comparable properties. example let's talk vectors:
function vector(x,y,z){ this.comp = function(){ // assuming these floats may wish create comparable level of // precision. gets point across. return x + (y * 10) + (z * 100); } } then when set vectors:
var v1 = new vector(1,1,1); var v2 = new vector(1,0,1); v1.comp() > v2.comp() // true this works of course if dealing objects can broken down simple numeric expression of value, upside implementation code basic effect pretty low , go far make object function returns numeric expression of it's component parts.
function vector(x,y,z){ var v = function v(){ return v.x + (v.y * 10) + (v.z * 100); } v.x = x; v.y = y; v.z = z; return v; } now have benefits of object easy numeric comparisons , it's kinda terse.
Comments
Post a Comment