深拷贝 浅拷贝

浅拷贝:Object.assign

var obj={name:'huahua', age:18, likes: {eat:true}}

var obj_q = Object.assign({},obj)
// obj_q={name:'huahua', age:18, likes: {eat:true}}

obj.name='haha'
//obj={name:'haha', age:18, likes: {eat:true}}
//obj_q={name:'huahua', age:18, likes: {eat:true}}

obj.likes.eat=false
//obj={name:'haha', age:18, likes: {eat:false}}
//obj_q={name:'huahua', age:18, likes: {eat:false}}

深拷贝:JSON.parse(JSON.stringify(object))

缺点:会忽略掉函数和 undefined
var obj={name:'huahua', age:18, likes: {eat:true}}

var obj_s=JSON.parse(JSON.stringify(obj))
//obj_s={name:'huahua', age:18, likes: {eat:true}}

obj.name='haha'
//obj={name:'haha', age:18, likes: {eat:true}}
//obj_s={name:'huahua', age:18, likes: {eat:true}}

obj.likes.eat=false
//obj={name:'haha', age:18, likes: {eat:false}}
//obj_s={name:'huahua', age:18, likes: {eat:true}}

你可能感兴趣的:(深拷贝 浅拷贝)