Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
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 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda