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

129 Views Asked by At

I want to keep two JavaScript variables in sync when I run a function. The variable that is to be pointed to is in an object. The code I have so far is 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 I do something similar to this without using the dreaded eval? Keep in mind that I want this function to be universal i.e. I want it to work with anyone's objects.

Thanks in advance.

Clarification edit: This is client side. I essentially want a variable that is a "pointer" to another variable (maybe not in the strict definition sense). I have made a function which can sync the variables, but it uses eval, which makes me skeptical. The "universal" part is that I can make tvar point to anything which will sync it. For example, if you include the above code, you can then:

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

Thus making it "universal" as varobj.tvar can "point" to anything to keep it in sync.

1

There are 1 best solutions below

1
On BEST ANSWER

You can use setters and getters to make a "virtual" property on the window named thevar, which mirrors to 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 you really want to do that is another question entirely.