Javascript: dynamic global variable

I have a global variable that looks like this:

var socket_x = 'whatever';

The fact is that "x" will depend on the user's session. Let them say that the user ID is 123, I want the global variable to be:

var socket_123 = 'whatever';

Thus, each user view will have its own set of sockets as a global variable.

I just don't know how to do this.

I know I can use:

eval('socket_' + userId)   = 'whatever'; //not recommended
window['socket_' + userId] = 'whatever'; //best

but if I want to declare a global variable like this, it will not work:

var eval('socket_' + userId) = 'whatever';

Can someone help me on this?

Thank.

PS: I know that "eval" should not be used for this, but it is just for illustration.


EDIT:

Thanks for your answer, all of you, but it just doesn't work.

, ( , , php javascript):

var socket_<?php echo $_SESSION['user_id'];?> = io.connect( 'http://pubsub.pubnub.com', pubnub_setup_private );

, :

window['socket_'+actual_user_id]= io.connect( 'http://pubsub.pubnub.com', pubnub_setup_private );

.

, :

eval('socket_'+actual_user_id).emit( 'all', msg_all );

, :

window['socket_'+actual_user_id].emit( 'all', msg_all );

, 2 :

  • , eval .
  • eval , . , "var" , "var" , eval .

, eval, , .

PS: .

+3
2
window['socket_'+userId] = "whatever";

. eval - , .

:

socket[userId] = "whatever";
+4

, window , . :

var myVar = 'hello';
alert( window.myVar );

... "" (, , ).

EDIT: , window, window[xxx] = yyy var xxx = yyy. , , . , , : http://jsfiddle.net/2hYfa/

+1

All Articles