简体   繁体   English

为什么即使在javascript中在本地范围内为其赋值之后,全局变量仍未定义

[英]Why does global variable stay undefined even after assigning value to it in a local scope in javascript

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. 我接受在mousemove事件监听器的匿名函数中指定mouseX来引用在函数外声明的全局变量。 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. 您正在设置事件处理程序的“load”处理程序中记录“mouseX”的值。 No events have happened yet, so the variable is still undefined . 尚未发生任何事件,因此变量仍未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. 这些变量可用的,如果你在事件处理程序中放置一个console.log()调用,或者某些“mousemove”事件发生代码运行,那么你会看到值正在更新。

我将变量的名称从mouseX更改为mouseXX并且它可以工作,不确定它为什么工作,也许jquery命名空间搞乱变量名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM