【问题标题】:Closure confusion, share global variable between function闭包混淆,函数间共享全局变量
【发布时间】:2016-12-12 12:50:45
【问题描述】:
    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);

    });

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

【问题讨论】:

  • data = data - 这样想……你怎么知道哪个数据是哪个
  • 您的socket.on 处理程序正在遮蔽外部data

标签: javascript jquery node.js socket.io


【解决方案1】:

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

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

要访问全局变量“数据”,将局部变量重命名为其他名称:

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

【讨论】:

  • 更可能是data = d; 的意图是
  • 几乎可以肯定 OP 想要 data = d,因为她稍后在 click 处理程序中尝试访问 data
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-14
  • 2018-03-16
  • 1970-01-01
  • 1970-01-01
  • 2016-12-27
  • 2017-08-19
相关资源
最近更新 更多