How can I change a property of an object using a reference variable?

I am trying to simplify the process by pointing to some properties with local variables. When I change the value of the array, the property changes as well (as expected). Strings and numbers do not change in the corresponding object properties. Is it possible to change properties using a reference variable?


var obj = {
    prop: 0,
    prop2: 'a',
    prop3: [],

    iterate: function() {
        var ref = obj.prop,
            ref2 = obj.prop2,
            ref3 = obj.prop3,
            i = 0;

        ref++;
        ref2 = 'b';
        ref3[i] = 'b';

        console.log(obj.prop, obj.prop2, obj.prop3);
        //0, 'a', ['b']

        obj.prop++;
        obj.prop2 = 'b';
        obj.prop3[i] = 'b';

        console.log(obj.prop, obj.prop2, obj.prop3);
        //1, 'b', ['b']
    }
}

obj.iterate();

      

+3


source to share


1 answer


pointing to some properties with local variables

You can not. JavaScript has no pointers. All variables store values.

When I change the value of the array, the property also changes (as expected).

Not really. You are mutating an array object. The property hasn't changed, it still contains a reference to the array.

Why aren't strings or numbers changing in their respective object properties?



Strings and numbers are primitive values ​​- you cannot mutate them. You are reassigning the variable with a new value. You are not reassigning a property, thereby not changing it.

The same happens for arrays and other object when reassigning a variable - ref3 = [];

does not change the property.

Is it possible to change properties via a reference variable?

Not. You can use the operator with

, but it is despised. Better to be explicit about the properties of the object.

+4


source







All Articles