JavaScript doesn't have operator overloading, and > doesn't call any methods on your objects, so p1 < p2 won't use your equals or compareTo.
To do that comparison, you'd use:
document.writeln(p1.compareTo(p2) < 0);
That said, you can implement valueOf and have it return age. valueOf does get called as part of > between objects:
function Person(age) {
this.age = age;
this.name = null;
}
Object.defineProperty(Person.prototype, "valueOf", {
value: function () {
return this.age;
},
writable: true,
configurable: true,
});
Or in code written since ES2015 became universally-supported in non-obsolete browsers:
class Person {
constructor(age) {
this.age = age;
this.name = null;
}
valueOf() {
return this.age;
}
}
Live Example:
class Person {
constructor(age) {
this.age = age;
this.name = null;
}
valueOf() {
return this.age;
}
}
const p1 = new Person(10);
const p2 = new Person(20);
console.log("p1 < p2: " + (p1 < p2)); // true
console.log("p1 > p2: " + (p1 > p2)); // false
Beware though that p1 == p2 and p1 === p2 will always be false, even if age is the same:
class Person {
constructor(age) {
this.age = age;
this.name = null;
}
valueOf() {
return this.age;
}
}
const p1 = new Person(10); // Same age
const p2 = new Person(10); // Same age
console.log("p1 == p2: " + (p1 == p2)); // false!
console.log("p1 === p2: " + (p1 === p2)); // false!
valueOf is invoked when the JavaScript engine needs to convert the object to a primitive; it doesn't do that for == or === unless it has to because the other operand is a primitive. So you'd have to define equals and explicitly call it (p1.equals(p2)), or force the comparison to be between the primitives (+p1 === +p2), which is error-prone.