在javascript中将数据公开到全局范围

时间:2016-08-04 13:19:25

标签: javascript jquery node.js socket.io

socket.on('connected', function(rand){

      socket.on('draw_'+rand, function(){


      });
    });

//I want to get rand here

function abc(){
}

由于某种原因,我无法将函数abc放在socket.on中,那么如何将rand传递给函数abc?如何将其暴露到全球范围?

1 个答案:

答案 0 :(得分:0)

var rand = null;
socket.on('connected', function(rand_){
  rand = rand_;
  socket.on('draw_'+rand, function(){


  });
});

//I want to get rand here
alert(rand);
function abc(){
}

只需加入全局命名空间即可。否则通过常数:

rand = null;
socket.on('connected', function(rand_){
  rand = rand_;
  socket.on('draw_'+rand, function(){


  });
});

//I want to get rand here
alert(rand);
function abc(){
}

但请注意:JS执行异步,这意味着您的rand将被更改为“null”,稍后它将从连接的侦听器获取其新值。 问候