【问题标题】:expose data to global scope in javascript在 javascript 中将数据公开到全局范围
【发布时间】:2016-12-10 15:29:54
【问题描述】:
socket.on('connected', function(rand){

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


      });
    });

//I want to get rand here

function abc(){
}

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

【问题讨论】:

    标签: javascript jquery node.js socket.io


    【解决方案1】:
    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”,稍后它将从连接的侦听器获取新值。 问候

    【讨论】:

      猜你喜欢
      • 2011-03-17
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      • 2017-01-20
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      • 1970-01-01
      相关资源
      最近更新 更多