Playing around with Javascript objects is fun, and annoying:
const MyObject = function(value) {
let _myObject = {
[Symbol.valueOf]() {
return value
},
[Symbol.toPrimitive]() {
return value
},
}
return _myObject
}
let o = new MyObject("a")
let p = new MyObject("b")
o == "a"
# true
p == "a"
# false
o < p
# true
p < o
# false
p + "-foo"
# 'p-foo'
Having custom objects behave like primitive types looks potentially useful and intuitive! Until you try something like this:
let o = new MyObject("a")
let p = new MyObject("a")
o == "a"
# true
p == "a"
# true
o == p
# false
Javascript will (quite sensibly) return false
when comparing two objects for equality.
Would there be any way to hack around the apparent “inconsistency” arising in a case like this? (Maybe some clever usage of proxies/Proxy handlers? )
Can I intercept/trap object behavior on comparison for equality
No, you can't. The behavior of ==
is governed by the IsLooselyEqual abstract operation in the specification, which just hands off to IsStrictlyEqual
when the operands both have the same type (and all objects are considered the same type in JavaScript). With the IsStrictlyEqual operation (===
), when both of the operands are objects, the result is based entirely on whether they're the same object. There's no trap in there that you can hook into, not even with a Proxy.