My understanding of the closure property is that every variable inside in a function scope has access to all the variables in the parent scope(s) the function is in,
So considering this definition I don't understand the behavior of my code below:
var mouseX, mouseY;
window.onload = function() {
this.addEventListener('mousemove', function() {
mouseX = event.clientX;
mouseY = event.clientY
}); // mouseX and mouseY are defined
petObj = new Pets();
}
function Pets(){
document.getElementById('imageList').addEventListener('mouseenter',function()
{
console.log(mouseX)} //undefined mouse X!!!
}
I accept the assignation of mouseX inside the anonymous function for mousemove event listener to reference the global variable declared outside the function. But as you can see it stays undefined outside the scope of the anonymous function
You're logging the value of "mouseX" inside the "load" handler that sets up the event handler. No events have happened yet, so the variable is still undefined.
The variables are available, and if you put a console.log() call inside the event handler, or somewhere else such that the code will run after some "mousemove" events have happened, you'll see the values being updated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With