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

140
Visualizações
Why does using "this" on an checkbox event listener not return the dom object, but rather the window object?

I have an event listener on a checkbox that passes a few arguments using "this", however for some reason it doesn't work.

Upon sending "this" to the console, I can see that unlike my other event listeners that I'm using for text input and select nodes, that it's returning the entire window object

The code I'm using:

document.getElementById("nightMode").addEventListener('change', () => {
    console.log(this)
})

What I would expect to see in console:

<input id="nightMode" type="checkbox" />

What is actually being sent to the console:

Window {window: Window, self: Window, document: document, name: '', location: Location, …}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

It's because you're using an arrow function ( () => { ... } ). Replace it with a normal function ( function() { ... } ).

Arrow functions don't have a this of their own. It cannot change; this inside an arrow function will always point to whatever this was at the point in time when the function was declared.

about 4 years ago · Juan Pablo Isaza Relatório

0

use this code instead:

<input id="nightMode" type="checkbox" onchange="alert(this)">
about 4 years ago · Juan Pablo Isaza Relatório

0

That's because when you use arrow function, you have binded this of your global scope ( Window ) to your handler function.

Try to use normal function decalration instead: function () { ... }

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