关闭混乱,共享函数之间的全局变量

时间:2016-08-06 04:21:34

标签: javascript jquery node.js socket.io

    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);

    });

出于某种原因,我无法将click事件放入socket.on,因为它正在侦听服务器。但我希望它的回调是data。我试图做data = data并期望我的点击回调能够获取数据,但它仍然是空的。

1 个答案:

答案 0 :(得分:1)

您的局部变量优先于全局变量:

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

访问全局变量&#34;数据&#34;将局部变量重命名为其他内容:

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.
});