Object.prototype.num = 1; // 原型链顶端
var person1 = {
name: ‘ytao‘,
age: 18,
sex: ‘male‘,
height: 165,
weight: 100,
children: {
first:{
name: ‘张小一‘,
age: 13
},
second:{
name: ‘张小二‘,
age: 12
},
third:{
name: ‘张小三‘,
age: 11
},
},
car: [‘Benz‘, ‘Mazda‘]
}
var person2 = deepClone(person1, person2);
person2.name = ‘lisi‘;
person2.children.forth = {
name: ‘张小四‘,
age: 1
};
person2.car.push(‘BYD‘);
// 深拷贝
function deepClone(origin, target){
var target = target || {},
toStr = Object.prototype.toString,
arrType = ‘[object Array]‘;
for(var key in origin){
if(origin.hasOwnProperty(key)){
if(typeof(origin[key]) === ‘object‘ && origin[key] !== null){
if(toStr.call(origin[key]) === arrType){
target[key] = [];
} else {
target[key] = {};
}
deepClone(origin[key], target[key]); // 递归处理
}else{
target[key] = origin[key];
}
}
}
return target;
}
console.log(person1);
console.log(person2);