function deepClone(target, origin){
var target = target || {},
toString = Object.prototype.toString,
ArrStr = "[object Array]";
for(var prop in origin){
if(origin.hasOwnProperty(prop)){
if(origin[prop] !== null && typeof(origin[prop]) === 'object'){
target[prop] = toString.call(origin[prop]) === ArrStr ? [] : {};
deepClone(target[prop], origin[prop]);
}else{
target[prop] = origin[prop];
}
}
}
return target;
}
我们来测试一下
var a = {
a: 12,
b: '123',
c: {
d: [1,2,3],
f: function(){
console.log("fun run");
},
g: [
{
name: 'a',
age: 18
}
]
},
k: null,
m: undefined,
l: true,
j: function(){
console.log("....j fun run");
}
}
var b = {};
deepClone(b, a);
a.a = 10000;
b.a // 12 没有被改变
网友评论