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
I changed the name of my variable from mouseX to mouseXX and it works,not sure why it worked ,maybe the jquery namespace was messing with the variable name
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments