Comparing objects in Javascript using equals and compareTo methods

I am trying to implement custom equalities and relational operations using the equals and compareTo methods. However, I get the wrong results. Please help me understand where I am doing wrong.

var Person = function () { this.age = null; this.name = null; }; Person.prototype.equals = function (that) { if (this.age === that.age) return true; else return false; }; Person.prototype.compareTo = function (that) { return this.age - that.age; }; var p1 = new Person(); var p2 = new Person(); p1.age = 10; p2.age = 20; document.writeln(p1 < p2); // this should be true but evaluates to false. 
+4
source share
1 answer

JavaScript does not have operator overloading, and > does not call any methods for your objects, so p1 < p2 do not use your equals or compareTo .

To make this comparison, you should use:

 document.writeln(p1.compareTo(p2) < 0); 

However, you can implement valueOf and return it age . valueOf gets called as part > between objects.

 var Person = function() { this.age = null; this.name = null; }; Person.prototype.valueOf = function() { return this.age; }; var p1 = new Person(); var p2 = new Person(); p1.age = 10; p2.age = 20; snippet.log("p1 < p2: " + (p1 < p2)); // true snippet.log("p1 > p2: " + (p1 > p2)); // false 
 <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.imtqy.com/simple-snippets-console/snippet.js"></script> 

Beware , however p1 == p2 and p1 === p2 will always be false . valueOf is called when the JavaScript engine must convert the object to a primitive; it does not do this for == or === if it is not, because the other operand is primitive. Thus, you will need to define equals and explicitly call it ( p1.equals(p2) ), or force the comparison to be between primitives ( +p1 === +p2 ) that are error prone.

+6
source

All Articles