5

I'm trying to pass a reference to a variable and then update the contents in javascript, is that possible? For example a simple (fail) example would be...

var globalVar = 2;

function storeThis ( target, value ) {
    eval(target) = value;
}

storeThis( 'globalVar', 5);
alert('globalVar now equals ' + globalVar);

This of course doesn't work, can anyone help?

3 Answers 3

4

Eval does not return a value.

This will work:

window[target] = value;

(however, you are not passing the reference, you're passing the variable name)

Sign up to request clarification or add additional context in comments.

4 Comments

digitalfresh is right, eval is for evaluation of statement so you probably need to create one e.g eval("window."+ target + "= " + value + ";"); but becarefull of too much recursion.
Yeah, but why eval at all? This is definitely not one of the few situations where eval is appropriate.
Bingo! Thank you both LFI and DigitalFresh, that worked a treat.
still open to better ways jasongetsdown!
3

In this case the code in storeThis already has access to globalVar so there's no need to pass it in.

Your sample is identical to:

var globalVar = 2;

function storeThis(value) {
    globalVar = value;
}

storeThis(5);

What exactly are you trying to do?

Scalars can't be passed by reference in javascript. If you need to do that either use the Number type or create your own object like:

var myObj = { foo: 2 };

Comments

2

If you really want to use eval, you could use the following:

var globalVar = 2;

function storeThis( target, value ) {
    eval( target + ' = ' + value );
}

storeThis( 'globalVar', 5 );
alert('globalVar now equals ' + globalVar);

1 Comment

In this case, if value is a string, the eval() will treat it as a variable (if it's one word), invalid code (if it's more than one word that javascript doesn't understand) or an expression (if it's a valid javascript expression).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.