[英]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);
});
由於某種原因,我無法將click事件放入socket.on中,因為它正在監聽服務器。 但是我想要它的回調是data
。我試圖做data = data,並希望我的點擊回調能夠獲取數據,但它仍然為空。
您的局部變量優先於全局變量:
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.
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.