一啤月、深拷貝與淺拷貝
深拷貝和淺拷貝只針對(duì)Object,Array這些復(fù)雜的引用對(duì)象畸冲。
淺拷貝嫉髓,只復(fù)制對(duì)象的引用的地址,不會(huì)再內(nèi)存中開(kāi)辟新的棧內(nèi)存邑闲,當(dāng)改變?cè)瓉?lái)obj的屬性時(shí)算行,newObj的屬性也會(huì)發(fā)生改變。
二苫耸、淺拷貝實(shí)現(xiàn)
function shallowCopy (obj) {
var newObj = {}
for (var item in obj) {
if (obj.hasOwnProperty(item)){
newObj[item] = obj[item]
}
}
return newObj
}
var obj = {
a:1,
arr:[2,3]
}
var shallowObj = shallowCopy(obj)
console.log(shallowObj)
shallowObj.arr[1] = 10
console.log(obj.arr[1])//同為10
三州邢、深拷貝的實(shí)現(xiàn)
深拷貝是將原對(duì)象遞歸復(fù)制,在內(nèi)存中開(kāi)辟新的棧內(nèi)存褪子,原對(duì)象和深拷貝對(duì)象不再指向同一個(gè)地址量淌。
兩種辦法,一是遞歸進(jìn)行淺拷貝嫌褪,二是JSON解析
JSON復(fù)制:優(yōu)點(diǎn)簡(jiǎn)單呀枢,缺點(diǎn)無(wú)法復(fù)制函數(shù),原型鏈沒(méi)有了
function deepCopy (obj) {
var newObj = JSON.parse(JSON.stringify(obj))
return newObj
}
var obj = {
a:'1',
test:{
old:'小濤濤',
new:'小瑩瑩'
}
}
var deepObj = deepCopy(obj)
console.log(deepObj)
deepObj.test.old = '小二貨'
console.log(obj.test.old)//小濤濤
console.log(deepObj.test.old)//小瑩瑩
function deepCopy2 (obj) {
var newObj2 = {}
for (var i in obj) {
if (typeof(obj[i]) === 'object' && obj[i].constructor === Object) {
newObj2[i] = {}
deepCopy2(obj[i])
} else {
newObj2[i] = obj[i]
}
}
return newObj2
}
function deepCopy2(p, c) {
var c = c || {};
for (var i in p) {
if (typeof p[i] === 'object') {
c[i] = (p[i].constructor === Array) ? [] : {};
deepCopy2(p[i], c[i]);
} else {
c[i] = p[i];
}
}
return c;
}
var obj2 = {
a:'1',
test:{
old:'小濤濤',
new:'小瑩瑩'
}
}
var deepObj2 = deepCopy2(obj2)
console.log(deepObj2)