简体   繁体   中英

Why do variables in object-nested array not change?

function Dealership = function(){
this.car1="Honda";
this.car2="Chevy";
this.car3="Toyota";
this.carList=[this.car1,this.car2,this.car3];
};

var tomsauto = new Dealership();
tomsauto.car2="Subaru";
console.log(tomsauto.carList); //returns honda chevy toyota

I'm confused as to how the array is processed. Is it static, holding only the variable values it had at instantiation, or should "this.car1" change when I change tom.car1?

When you create the array via that array instantiation expression, the runtime system copies the values of each of those object properties into the array. If you later change the values of the properties, they'll change independently of the array elements.

There's no way in JavaScript to make a property of one object "mirror" the property of another. (Well, no intrinsic way; you can write code to do it.)

As Teemu said: your carList is populated with values, not references.

An easy workaround is to change it to a function getCarList :

var Dealership = function () {
    this.car1 = "Honda";
    this.car2 = "Chevy";
    this.car3 = "Toyota";
    this.getCarList = function() {
        return [this.car1, this.car2, this.car3];
        }
};

var tomsauto = new Dealership();
tomsauto.car2 = "Subaru";
console.log(tomsauto.getCarList());

I think you are running into that problem because of how closures work in JavaScript.

When you declare the function as you did, the value of car1, car2, car3 get evaluated in that scope and then are assigned to the array.

When you do the new Dealership() bit, the values of that array are pretty much set as they were when the function was evaluated. After you do

tomsauto.car2 = "Subaru";

the value of car2 will change, but the array will not because the values are not being re-evaluated.

If you want to know more about how and why, I suggest you read more about closures in javascript and functional languages in general.

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