Luke Neat
Luke Neat

Reputation: 55

Updating Javascript Objects

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?

Upvotes: 3

Views: 103

Answers (3)

gen_Eric
gen_Eric

Reputation: 227200

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;
}

Upvotes: 4

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99889

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;

Upvotes: 1

chrislondon
chrislondon

Reputation: 12031

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);

Upvotes: 1

Related Questions