2016-08-04 36 views
0
socket.on('connected', function(rand){ 

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


     }); 
    }); 

//I want to get rand here 

function abc(){ 
} 

由於某些原因,我無法將函數abc放在socket.on中,那麼如何將rand傳遞給函數abc?如何將其暴露給全球範圍?在JavaScript中向全局範圍公開數據

回答

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將alterted爲「零」,後來它會得到從連接監聽器的新值。 問候