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