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
Post a Comment