Search code examples
javascriptobjectcompareobject-comparison

How can my class instance implicitly return a number when compare with another instance?


Look at this example:

var d1 = new Date(2016,4,1);
var d2 = new Date(2016,4,2);
if (d2 > d1){ .... }

As you can see in date object, when you compare two instance then they return implicitly getTime() method of this instances.

I want to do exact same thing with my object.

Imagine my class is something like this:

var myClass = function (arg1,arg2,arg3){
   ....
   ....
   ....
   this.myNumber = function (){
         return arg1 + arg2+ arg3;
   }
}

and I want when I compare two instances of my class then it compare the value of their myNumber() method.


Solution

  • Define a valueOf() method for your class:

    var myObj = function(arg1,arg2,arg3) {
       ....
       ....
       ....
       this.valueOf = function() {
         return arg1 + arg2+ arg3;
       }
    }
    

    See a JS Bin demo.