Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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, …}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading