Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - pass objects by reference [duplicate]

Possible Duplicate:
How can I store reference to a variable within an array?

Consider the following code:

var a = 'cat';
var b = 'elephant';
var myArray = [a,b];

a = 'bear';

myArray[0] will still return 'cat'. Is there a way to store references in the array instead of clones, so that myArray[0] will return 'bear'?

like image 745
indieman Avatar asked Dec 05 '22 16:12

indieman


2 Answers

While I agree with everyone else saying that you should just use myArray[0] = whatever, if you really want to accomplish what you're trying to accomplish you could make sure that all you variables in the array are objects.

var a = {animal: 'cat'},
    b = {animal: 'elephant'};

var myArray = [a, b];

a.animal = 'bear';

myArray[0].animal is now 'bear'.

like image 74
hobberwickey Avatar answered Dec 23 '22 23:12

hobberwickey


No. JavaScript doesn't do references in that way.

like image 40
Gareth Avatar answered Dec 23 '22 23:12

Gareth