Reputation: 55
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
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
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
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