Object.assign和序列/反序列
阿新 • • 發佈:2018-11-12
Object.assign
let testObj = { a:[1,2,4], b:{ name:'ls', school:['huf','yelu'], parent:{ father:'lili', mother:'xixi' } }, c:function() { alert(this.b.name) } } let newObj= Object.assign(testObj); newObj.b.parent.mother = 'qinghua'; newObj.a[0] = 4; console.log(testObj.b.parent.mother);//qinghua console.log(testObj.a[0])//4 console.log(newObj.c);//ƒ () {alert(this.b.name)}
陣列和物件兩個引用的是同一塊記憶體
序列/反序列
let testObj = { a:[1,2,4], b:{ name:'ls', school:['huf','yelu'], parent:{ father:'lili', mother:'xixi' } }, c:function() { alert(this.b.name) } } let newObj = JSON.parse(JSON.stringify(testObj)); newObj.b.parent.mother = 'qinghua'; newObj.a[0] = 4; console.log(testObj.b.parent.mother);//xixi console.log(testObj.a[0])//1 console.log(newObj.c);//undefined
陣列和物件引用的不是同一塊記憶體,但是函式克隆失敗