简体   繁体   English

如何通过引用变量更改对象属性?

[英]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. JavaScript没有指针。 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 = []; 当您重新分配变量时,数组和其他对象ref3 = [];发生同样的情况 - 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. 不。你可以使用with声明 ,但这是鄙视的。 Better be explicit about object properties. 最好明确对象属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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