JavaScript实现对象深拷贝的方式(包含函数克隆)
//创建一个对象
let s={
name:'yds',
age:21,
data:{
p:'ws',
sys:'root'
},
arr:[12,56,78],
fn:function(){
console.log('嗨')
}
};
//自定义一个深拷贝递归函数
function deepClone(obj){
let clone = Array.isArray(s)?[]:{};
for (const key in obj) {
let item = obj[key];
if(item){
//实现方法的克隆
if(item instanceof Function){
clone[key] = new Function('return '+item.toString())()
}
else if(item instanceof Object ){
clone[key] = deepClone(item);
}
else {
clone[key] = item;
}
}
}
return clone;
}
//可以实现复杂的深拷贝,但无法克隆函数
//let clone = JSON.parse(JSON.stringify(s));
//无法实现复杂的深拷贝,对于复杂对象只复制其引用
//let clone = {...s}
//自定义递归 实现了函数的克隆
let clone = deepClone(s);
s.name = 'hmy';
s.data.p='ms';
console.log(s);
console.log(clone);
clone.fn();
控制台输出:
{name: 'hmy', age: 21, data: {…}, arr: Array(3), fn: ƒ}
{name: 'yds', age: 21, data: {…}, arr: {…}, fn: ƒ}
嗨

浙公网安备 33010602011771号