I am trying to play with objects alongside with Symbol.toPrimitive
symbol in order to convert objects to primitives.
I used this code:
function UserEq(name) {
this.name = name;
this[Symbol.toPrimitive] = function (hint) {
alert("hint is: " + hint);
return 0;
};
}
function objectEqualityCheck() {
let user1 = new UserEq("John");
let user2 = new UserEq("Rambo");
if (user1 == user2) alert("Equal!");
}
And I expect two conversions resulting in alert Equal!
, but that is not what's hapenning...
When used like user1 == 0
all works fine (conversion is to number
though).
Why when two objects are compared, it does not work?
EDIT: it doesn't work with ===
as well.
The first rule in the docs for ==
defines this
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
If Type(x) is the same as Type(y), then Return the result of performing Strict Equality Comparison x === y.
user1 == user2
Here you're comparing same type so there's no type conversion happens at all
ToPrimitive is called only under these conditions