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

copy和obj都指向同一个对象,copy.cat和obj.cat指向的也都是同一个对象,改变copy.cat.name实际上就是在改变那个对象的值,从而使obj.cat.name的值也改变了。

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 getType(target) {
	return Object.prototype.toString.call(target).slice(8, -1);
}
// 递归处理
function deepCopy(target) {
	if (getType(target) === "Array") {
		let arr = [];
		for (let i in target) {
			arr.push(deepCopy(target[i]));
		}
		return arr;
	} else if (getType(target) === "Object") {
		let obj = {};
		for (let i of Object.keys(target)) {
			obj[i] = deepCopy(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(deepCopy(val));
		});
		return set;
	} else if (getType(target) === "Map") {
		const map = new Map();
		for (let item of target) {
			map.set(deepCopy(item[0]), deepCopy(item[1]));
		}
		return map;
	} else if (!(target instanceof Object)) {
		// 原始类型
		return target;
	} else {
		console.error("未拦截的类型 ", target);
	}
}
// 封装成一个处理函数
function handleDeepCopy(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 = handleDeepCopy(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

这样就手动实现了深拷贝,这种方式覆盖了所有常用类型,如果遇到没有覆盖的类型,再往deepCopy函数里加处理语句即可。

以上代码并非完美的,它仍然无法处理循环引用的问题。

最后更新于