let aa = {a: 1, b: {c: 2}}
let bb = aa
bb.a = 2
console.log(bb)
// {a:2, b: {c:2}}
console.log(aa)
// {a:2, b: {c:2}}
bb.b.c = 3
console.log(bb)
// {a:2, b: {c:3}}
console.log(aa)
// {a:2, b: {c:3}}
// 方式一:通过Object.create实现
function shallow (obj) {
if (obj === null || typeof obj !== 'object') {
return obj
} else {
return Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj)
)
}
}
// 方式二:通过Object.assign实现
let aa = {a: 1, b: {c: 2}}
let bb = Object.assign({}, aa)
bb.a = 2
console.log(bb)
// {a:2, b: {c:2}}
console.log(aa)
// {a:1, b: {c:2}}
bb.b.c = 3
console.log(bb)
// {a:2, b: {c:3}}
console.log(aa)
// {a:1, b: {c:3}}
// 递归方式
// 不要使用Object.keys遍历:不遍历可枚举的的原型链属性
// 方法一:
function deepCopy (obj) {
let target = {}
if (obj === null || typeof obj !== 'object') {
return obj
}
for (let key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if (typeof obj[key] === 'object') {
target[key] = deepCopy(obj[key])
} else {
target[key] = obj[key]
}
}
}
return target
}
// 方法二:
function deepCopy (obj, clone = Array.isArray(obj) ? [] : {}) {
if (obj != null && typeof obj === 'object') {
for (const [key, value] of Object.entries(obj)) {
clone[key] = deepCopy(value)
}
} else {
clone = obj
}
return clone
}
let aa = {a: 1, b: {c: 2}}
let bb = deepCopy(aa)
bb.a = 2
console.log(bb)
// {a:2, b: {c:2}}
console.log(aa)
// {a:1, b: {c:2}}
bb.b.c = 3
console.log(bb)
// {a:2, b: {c:3}}
console.log(aa)
// {a:1, b: {c:2}}
// 1. Date对象会变成字符串格式
let aa = {a: new Date()}
let bb = JSON.parse(JSON.stringify(aa))
console.log(aa)
// {a: Fri Mar 13 2020 18:26:03 GMT+0800 (中国标准时间)}
console.log(bb)
// {a: "2020-03-13T10:26:03.567Z"}
// 2. 函数会丢弃
let aa = {name: 'MuYi086', width: function () {}}
let bb = JSON.parse(JSON.stringify(aa))
console.log(aa)
// {name: "MuYi086", width: ƒ}
console.log(bb)
// {name: "MuYi086"}
// 3.NaN、Infinity、-Infinity会变成null
let aa = {a: NaN, b: Infinity, c: -Infinity, name: 'MuYi086'}
let bb = JSON.parse(JSON.stringify(aa))
console.log(aa)
// {a: NaN, b: Infinity, c: -Infinity, name: "MuYi086"}
console.log(bb)
// {a: null, b: null, c: null, name: "MuYi086"}
// 4.RegExp、Error对象会变成{}
let aa = {name: 'MuYi086', date: new RegExp('/d+/ig'), day:new Error('gg')}
let bb = JSON.parse(JSON.stringify(aa))
console.log(aa)
// {name: "MuYi086", date: //d+/ig/, day: Error: gg at <anonymous>:1:59}
console.log(bb)
// {name: "MuYi086", date: {}, day: {}}
// 5.丢失对象的constructor
function Person (name) {
this.name = name
}
let zz = new Person('MuYi086')
let yl = {nick: 'og', label: zz}
let copyed = JSON.parse(JSON.stringify(yl))
console.log(yl)
// {nick: "og", label: Person} label: Person {name: "MuYi086"}
console.log(copyed)
// {nick: "og", label: {name: "MuYi086"}}