acincognito
acincognito

Reputation: 1743

vue v2 value inside object inside class property changed although not altered

I'm using vue v2 to create an SPA. I declared an Offer class like this in the script section of my vue component:

class Offer {
       constructor(Tariff, TariffCopy, billing, at, fa, backs) {
       this.Tariff = Tariff;
       this.BaseTariff = TariffCopy;
    }

    changeSAC(p1, p2) {
       ...
       this.Tariff.provAufwand.SO = this.BaseTariff.provAufwand.SO + Number(p1);
    }
}

Tariff and TariffCopy are objects initialized from a custom class called Tariff also declared in the script section of the same component. Basically they contain the same values, but Tariff is open to value changes, while BaseTariff's values shall remain unchanged.

class Tariff{
    constructor(provAufwand) {
        this.provAufwand = provAufwand;
    }
}

where

provAufwand= {
    SO: 1,
    HO5: 2,
    HO10: 3,
    HO20: 4
}

When calling Offer.changeSAC(p1,p2) (p1 and p2 are bound to number inputs via v-model="p1" and v-model="p2") the value of this.BaseTariff.provAufwand.SO is changed, too, although I never alter it in the code. Why is that? Where in my code are they connected?

Upvotes: 0

Views: 37

Answers (1)

Ana Liza Pandac
Ana Liza Pandac

Reputation: 4871

Assuming that you created your Tariff instances like these:

const provAufwand= {
    SO: 1,
    HO5: 2,
    HO10: 3,
    HO20: 4
};
const tariff = new Tariff(provAufwand);
const tariffCopy = new Tariff(provAufwand);

Then the reason why BaseTariff or tariffCopy is also changing when you changed tariff is that they are referencing the same provAufwand object.

When you passed provAufwand to the Tariff constructor, the parameter that was passed was not the actual value of the object but the reference to the object.

When you passed an object or an array to a function, then the argument is passed by reference.

This means that changing the value of the object/array inside the function affect the value of the same object/array outside the function.

To solve it, you can use the spread syntax when passing provAufwand when creating a new Tariff object.

const provAufwand= {
    SO: 1,
    HO5: 2,
    HO10: 3,
    HO20: 4
};
const tarrif = new Tariff({...provAufwand});
const tarrifCopy = new Tariff({...provAufwand});

This ensures that you are passing completely different objects when creating your class instances.

Upvotes: 1

Related Questions