Why are variables in an object-nested array not changing?

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 am confused about how the array is processed. Is it static, retaining only the values ​​of the variables that it had at creation, or should "this.car1" change when tom.car1 changes?

+3
source share
3 answers

As Teemusaid: yours is carListfilled with values, not links.

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());
+2
source

When you create an array using an array instance expression, the runtime system copies the values ​​to the array . , .

JavaScript "" . (, , , .)

+4

, - , JavaScript.

, , car1, car2, car3 .

Dealership(), , , . ,

tomsauto.car2 = "Subaru";

car2 , , .

, , javascript .

0

All Articles