Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a variable by reference in Javascript

Tags:

javascript

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?

like image 351
Julian Young Avatar asked Jul 30 '10 15:07

Julian Young


2 Answers

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)

like image 103
tcooc Avatar answered Oct 26 '22 22:10

tcooc


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 };
like image 36
jasongetsdown Avatar answered Oct 26 '22 22:10

jasongetsdown