Blue Ryno
Blue Ryno

Reputation: 143

How do I change an object property via a reference variable?

I'm trying to simplify a process by pointing to some properties with local variables. When I change the array value, the property changes as well (as expected). Strings and numbers don't seem to change in their corresponding object properties. Is it possible to change the properties via 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();

Upvotes: 3

Views: 1045

Answers (1)

Bergi
Bergi

Reputation: 664620

pointing to some properties with local variables

You cannot. JavaScript doesn't have pointers. All variables hold values.

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

Not really. You mutate the array object. The property hasn't changed, it still contains the reference to the array.

Why don't strings or numbers change in their corresponding object properties?

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

The same happens for arrays and other object when you reassign the variable - ref3 = []; doesn't change the property.

Is it possible to change the properties via a reference variable?

No. You could use a with statement, but this is despised. Better be explicit about object properties.

Upvotes: 4

Related Questions