3

I have the following object:

var obj1 = {};

obj1.obj2 = {
  prop1: 0
};

and the following function:

function func1() {
    var p = obj1.obj2.prop1;
    p += 2;
    return p;
 };

When updating 'p' it has not updated 'obj1.obj2.prop1'. Instead of 'p' pointing to the original object is it now it's own object by itself? If so how can I make 'p' a pointer?

Luke Neat
  • 55
  • 4

3 Answers3

4

When you do var p = obj1.obj2.prop1;, you are setting p to the value of prop1. So, when you update p, you're just updating the value set in p.

What you can do is set p to obj1.obj2. Then you can update p.prop1 and it should update obj1.

function func1() {
    var p = obj1.obj2;
    p.prop1 += 2;
    return p.prop1;
}
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
1

Javascript doesn't have pass-by-reference so you would have to do the following:

var obj1 = {};

obj1.obj2 = {
    prop1: 0
};

function func1(obj) {
    obj.obj2.prop1 += 2;
    return obj.obj2.prop1;
};

func1(obj1);
chrislondon
  • 12,487
  • 5
  • 26
  • 65
1

p += 2 is just assigning an other number to p, this isn't modifying the object pointed to by p.

Do this instead:

obj1.obj2.prop1 += 2;

or

var obj = obj1.obj2;
obj.prop1 += 2;
Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194