在javascript中保存类的原始状态[重复]

问题描述 投票:0回答:0

假设我有课

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

    getState(){
        return this.state;
    }

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

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

如果我这样做

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'}

为什么

const originalState
也变成了“绿色”? 有什么办法可以保存苹果的原始状态吗? 提前致谢

javascript
© www.soinside.com 2019 - 2024. All rights reserved.