javascript - What is an alternative to using 'eval' to accessing a variable by name to "sync" it with another? -


i want keep 2 javascript variables in sync when run function. variable pointed in object. code have far this:

var myname = "bob"; var thevar = ""; var varobj = {tvar: "myname"}; var syncvar = function() {     thevar = eval(varobj.tvar); };  syncvar(); alert(thevar); // bob myname = "eve"; syncvar(); alert(thevar); // eve 

how can similar without using dreaded eval? keep in mind want function universal i.e. want work anyone's objects.

thanks in advance.

clarification edit: client side. want variable "pointer" variable (maybe not in strict definition sense). have made function can sync variables, uses eval, makes me skeptical. "universal" part can make tvar point sync it. example, if include above code, can then:

myage = 20; varobj = {tvar: "myage"}; syncvar();  alert(thevar); // 20 myage = 100; syncvar(); alert(thevar); // 100 

thus making "universal" varobj.tvar can "point" keep in sync.

you can use setters , getters make "virtual" property on window named thevar, mirrors varobj.tvar:

object.defineproperty(window, 'thevar', {     get: function( ) { return window[varobj.tvar]    ; },     set: function(v) {        window[varobj.tvar] = v; } });  > varobj = { tvar: "bob" } > thevar = 1 > bob < 1 

whether or not want question entirely.


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -