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));
<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.
source share