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?

1

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.