[英]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.