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
数组和对象引用的不是同一块内存,但是函数克隆失败