js实现深拷贝(深复制)函数(多种数据类型全支持)

function DeepClone (obj) {
	if (obj === null || typeof obj !== 'object') return obj;
	var cpObj = obj instanceof Array ? [] : {};
	for (var key in obj) cpObj[key] = DeepClone(obj[key]);
	return cpObj;
}

var obj = {
	id: 1,
	name: 'xxx',
	sayName: function (a) {
		console.log('my name is ' + a);
	},
	childs: [
		{'a': 1}, 
		{'c': 'd'}, 
	],
	opts: {
		xxx: [1,2,'3'],
		aa: 'bb'
	},
};
var newObj = DeepClone(obj);
console.log(obj)
console.log(newObj)
obj.id = 2
console.log("obj.id", obj.id) // 2
console.log("newObj .id", newObj .id) // 1
obj.sayName('hah')
newObj.sayName('22')
obj.sayName = 3
console.log(obj.sayName) // 3
console.log(newObj.sayName) // function

觉得有帮助的小伙伴右上角点个赞~

在这里插入图片描述

扫描上方二维码关注我的订阅号~

你可能感兴趣的:(js,深拷贝,深复制,js,函数,对象)