0

Let's say I have a class

class Apple {
    constructor(color){
        this.state = {
            color: color
        }
    }

    getState(){
        return this.state;
    }

    setState(state){
        this.state = state;
    }

    turnGreen(){
        this.state.color = "Green";
    }
}

and if i do

let apple = new Apple("Red");

const originalState = apple.getState();

apple.turnGreen();             
console.log(apple.getState());   //{color: 'Green'}

apple.setState(originalState);
console.log(apple.getState());   //{color: 'Green'}

How come const originalState gets changed to 'Green' as well? And is there any way to save the original state of the apple? Thanks in advance

  • 1
    object has same reference https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language might help i guess – cmgchess Apr 08 '23 at 22:42
  • 1
    Easy fix: `const originalState = { ...apple.getState() };` – Konrad Apr 08 '23 at 22:44

0 Answers0