简体   繁体   English

封闭混乱,在功能之间共享全局变量

[英]Closure confusion, share global variable between function

    var data = null;

    socket.on('screen1', function (data) {

        data = data;
        console.log(data) // has something
    });

    $approve.click(function(){
        console.log(data) //null
        socket.emit('screen2', data);

    });

For some reason I can't put click event into socket.on because it's listening to the server. 由于某种原因,我无法将click事件放入socket.on中,因为它正在监听服务器。 But I want its callback which is the data .I tried to do data = data and expect my click callback is able to get the data but it's still null. 但是我想要它的回调是data 。我试图做data = data,并希望我的点击回调能够获取数据,但它仍然为空。

Your local variable takes precedence over the global variable: 您的局部变量优先于全局变量:

socket.on('screen1', function (data) { // <-- local variable "data"
    data = data;  // <-- both these "data" are the same variable!!
});

To access the global variable "data" rename the local variable to something else: 要访问全局变量“数据”,请将局部变量重命名为其他名称:

socket.on('screen1', function (d) {
    // Here I have no idea what your intention is. If I am
    // confused consider how the compiler is supposed to read
    // your mind.

    // You either wanted to do:
    d = data;

    // or data = d;

    // I cannot guess and neither can the compiler.
});

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

相关问题 Javascript-全局和局部变量之间的混淆 - Javascript - confusion between global & local variable JavaScript:闭包和全局函数之间的开销比较 - JavaScript: Overhead comparison between closure and a global function SAIKU UI 在视图之间共享全局变量 - SAIKU UI SHARE GLOBAL VARIABLE BETWEEN VIEWS 通用全局变量和对象(作为JavaScript中的变量)之间的混淆 - Confusion between a general global variable and object as a variable in javaScript 在带有JavaScript闭包的回调函数中,如何访问全局变量 - In callback function with Javascript closure, how to access the global variable 如何在TestCafe中的测试中的测试文件之间共享全局变量? - How to share a global variable between test files from a test in TestCafe? 如何在多个文件之间共享全局变量? - How do I share a global variable between multiple files? 如何在Meteor中的服务器和客户端代码之间共享全局变量 - How to share a global variable between server and client code in Meteor 可以在没有文件的情况下在两个函数之间共享全局变量吗? - Possible to share global variable between two functions without a file? jQuery全局变量访问混乱 - jQuery global variable access confusion
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM