分配给构造函数属性的对象是否可以进行深度克隆?

时间:2018-04-14 09:26:51

标签: javascript

我想对分配给this.state的对象进行“硬拷贝”,并在sayHello方法中更改副本。当我使用Object.assign时,它会更改this.state。我怎样才能解决这个问题?或者......我可以吗? ~~~~~~

class App {
    constructor() {
        this.state = {
            items: []
        }

    }

    sayHello() {

        //______I want to clone this.state so I can modify the copy____
        //______I use Object.assign()__________________________________

        let objCopy = Object.assign({}, this.state)

        //_____I change the copy_______________________________________
        objCopy.items.push({ text: "hi there" })

        //_____But the original was changed...nooooooooo!______________

        console.log(this.state);  // Changed!  { items: [ { text: 'hi there' } ] }


    }

}

let myApp = new App()

myApp.sayHello();

0 个答案:

没有答案