JavaScript浅拷贝和深拷贝

JavaScript浅拷贝和深拷贝

JavaScript引用类型的拷贝分为浅拷贝和深拷贝。
浅拷贝: 只拷贝对象的引用,而不是对象本身。
深拷贝:将当前对象的所有属性和方法完整拷贝。

浅拷贝

我们这里借助三点运算符实现浅拷贝
let obj = { a: 1, cat: { name: 1, age: 2, tags: ["小叮当"], }, }; let copy = { ...obj }; copy.cat.name = 2; console.log(copy.cat.name, obj.cat.name); // 2 2
这段代码可能会让人误以为浅拷贝会完整拷贝第一层的属性,但是其实并不是。
let obj = { a: 1, cat: { name: 1, age: 2, tags: ["小叮当"], }, }; let copy = { ...obj }; copy.cat = { a: 1 }; console.log(copy.cat, obj.cat); // { a: 1 } { name: 1, age: 2, tags: [ '小叮当' ] }
因为浅拷贝是是拷贝对象的引用,因此copy.cat = { a: 1 };是改变了copy.cat的引用,而obj.cat的引用却没有改变,还是原来的那个对象,因此最后两者的值不同。

深拷贝

JSON.parse(JSON.stringify(obj));能够实现深拷贝
let obj = { a: 1, cat: { name: 1, age: 2, tags: ["小叮当"], }, }; let copy = JSON.parse(JSON.stringify(obj)); copy.cat.age = 10; console.log(copy.cat.age, obj.cat.age); // 10 2
但是它存在一些问题。
  • 会抛弃对象的constructor,所有对象的constructor都会变为Object
  • 无法实现对函数、RegExp等特殊对象的克隆
  • 循环引用会报错
循环引用报错
let obj = { a: 1, age: obj.a, cat: { name: 1, age: 2, }, }; let copy = JSON.parse(JSON.stringify(obj)); copy.cat.age = 10; console.log(copy.cat.age, obj.cat.age); // ReferenceError: Cannot access 'obj' before initialization
手动实现深克隆
let obj = { a: 1, b: /1/g, cat: { name: 1, age: 2, callMe: function () { console.log("me"); }, }, set: new Set([1, 2, 3]), map: new Map([ [1, 2], [3, 4], ]), }; // 深拷贝函数 function deepCopy(target) { const wm = new WeakMap(); // 判断类型 function getType(target) { return Object.prototype.toString.call(target).slice(8, -1); } // 递归处理 function handleDeepCopy(target) { if (getType(target) === "Array") { let arr = []; for (let i in target) { arr.push(handleDeepCopy(target[i])); } return arr; } else if (getType(target) === "Object") { let obj = Object.create(Object.getPrototypeOf(target)); if (wm.has(target)) { // 解决循环引用,避免重复递归 return wm.get(target); } wm.set(target, obj); for (let i of Object.keys(target)) { obj[i] = handleDeepCopy(target[i]); } return obj; } else if (getType(target) === "Function") { const fn = target.toString(); return new Function("return " + fn)(); } else if (getType(target) === "RegExp" || getType(target) === "Date") { return new target.constructor(target); } else if (getType(target) === "Set") { const set = new Set(); target.forEach((val) => { set.add(handleDeepCopy(val)); }); return set; } else if (getType(target) === "Map") { const map = new Map(); for (let item of target) { map.set(handleDeepCopy(item[0]), handleDeepCopy(item[1])); } return map; } else if (!(target instanceof Object)) { // 原始类型 return target; } else { console.error("未拦截的类型 ", target); } } return handleDeepCopy(target); } // 封装成一个处理函数 // function deepCopy(target) { // if (getType(target) !== "Array" && getType(target) !== "Object") { // throw new Error("必须传入一个对象或者数组"); // } // let copy = Object.create(target.prototype || null); // for (let i in target) { // copy[i] = deepCopy(target[i]); // } // return copy; // } // 验证是否拷贝成功 const copyObj = deepCopy(obj); console.log(copyObj); /* [Object: null prototype] { a: 1, b: /1/g, cat: { name: 1, age: 2, callMe: [Function (anonymous)] }, set: Set(3) { 1, 2, 3 }, map: Map(2) { 1 => 2, 3 => 4 } } */ // 验证深拷贝 copyObj.cat.name = "阿花"; console.log(copyObj, obj); /* { a: 1, b: /1/g, cat: { name: '阿花', age: 2, callMe: [Function (anonymous)] }, set: Set(3) { 1, 2, 3 }, map: Map(2) { 1 => 2, 3 => 4 } } { a: 1, b: /1/g, cat: { name: 1, age: 2, callMe: [Function: callMe] }, set: Set(3) { 1, 2, 3 }, map: Map(2) { 1 => 2, 3 => 4 } } */ // 验证函数拷贝是否成功 copyObj.cat.callMe(); // me // 验证循环引用 const o = { a: {} }; o.a.o = o; console.log(deepCopy(o));
这样就手动实现了深拷贝,这种方式覆盖了所有常用类型,如果遇到没有覆盖的类型,再往deepCopy函数里加处理语句即可。