• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

111
Vistas
Can I intercept/trap object behavior on comparison for equality

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? )

about 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda