目的:将 cloneFather 拷贝给 cloneSon
let cloneFather = { item1: '1', item2: '2', arr: ['3'] }
let cloneSon = {}
浅拷贝
function extentCopy(obj) {
let o = {}
for (let i in obj) {
o[i] = obj[i]
}
o.uper = obj
return o
}
// cloneSon = extentCopy(cloneFather)
// cloneSon.arr.push('0')
// 问题:如果父对象的属性等于数组或另一个对象,那么子克隆改变,父对象跟着改变
// 如下 father 的 arr 变为 ['3', '0']
console.log(cloneSon, cloneFather);
深拷贝
可以解决浅拷贝的问题
function deepCopy(obj, item) {
let o = item || {}
for (let i in obj) {
if (typeof obj[i] === 'object') {
o[i] = (obj[i].constructor === Array) ? [] : {}
deepCopy(obj[i], o[i])
} else {
o[i] = obj[i]
}
}
return o
}
cloneSon = deepCopy(cloneFather)
cloneSon.arr.push('0')
console.log(cloneSon, cloneFather);