7

If I have an object like this:

obj = {a:{aa:1}, b:2};

and I want to create a shortcut variable (pointer to obj.a.aa) x like this:

x = obj.a.aa;

and then I want to assign the value 3 to obj.a.aa using x like this:

x = 3;  // I would like for obj.a.aa to now equal 3
console.log(obj.a.aa); // 1  (I want 3)

How can I set x up to result in the value 3 going into obj.a.aa?

I understand that obj.a.aa is a primitive, but how can I define a variable that points to it which I can then use to assign a value to the property?

ciso
  • 2,887
  • 6
  • 33
  • 58
  • 1
    pretty sure you can't. – Kevin B Apr 28 '14 at 15:38
  • Related: [Is JavaScript a pass-by-reference or pass-by-value language?](http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) and [Does JavaScript pass by reference?](http://stackoverflow.com/questions/13104494/does-javascript-pass-by-reference) – Jonathan Lonowski Apr 28 '14 at 15:45

3 Answers3

9

You cannot use x = value as that will not keep any references, just a copy. You would have to reference the parent branch in order to do so:

x = obj.a;

then set the value:

x.aa = 3;
3

Or, use a function:

var set_x = function(val){
  obj.a.aa = val;
}
YMMD
  • 3,730
  • 2
  • 32
  • 43
0

Of course you can't - you're not trying to modify the reference that is the name of the object property, you're trying to modify the object. To modify the object, you'll need a reference to the object.

That being said there's probably a creative way to do this. Create a function that takes as a constructor the object, and give the function a customer = setter or method that modifies the object reference. Something like this might work.

djechlin
  • 59,258
  • 35
  • 162
  • 290