Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override default behavior of comparison operators in JavaScript

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?

like image 740
Chetan Avatar asked Apr 11 '11 21:04

Chetan


People also ask

What is === operator in JavaScript?

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.

How many JavaScript comparison operators are there?

In JavaScript, there are two types of comparison operators: Type-converting (or Abstract) Strict.


2 Answers

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.

like image 117
Lee Irvine Avatar answered Oct 19 '22 20:10

Lee Irvine


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);
like image 6
HMR Avatar answered Oct 19 '22 21:10

HMR