简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM