克隆的概念
浅度克隆:原始类型为值传递,对象类型仍为引用传递。
-
深度克隆:所有元素或属性均完全复制,与原对象完全脱离,也就是说所有对于新对象的修改都不会反映到原对象中。
看一个浅克隆//浅克隆 function clone(obj) { var result = {}; for (key in obj) { result[key] = obj[key]; } return result; } var Person = { name: "jack", age: "18", Address: { province: "beijing" }, }; var New = clone(Person); console.log(Person.Address.province); //beijing New.Address.province = "shanghai"; console.log(Person.Address.province); //shanghai
在看一个深克隆
//深度克隆
function deepClone(obj) {
var result, oClass = isClass(obj);
if (oClass === 'Object') { //初始化result类型
result = {};
} else if (oClass === 'Array') {
result = [];
} else {
return obj;
}
for (key in obj) {
var copy = obj[key];
if (isClass(copy) == 'Object') {
result[key] = arguments.callee(copy);////递归调用
} else if (isClass(copy) == 'Array') {
result[key] = arguments.callee(copy);
} else {
result[key] = obj[key];
}
}
return result;
}
function isClass(o) {//判断传入的类型
if (o === null) return 'Null';
if (o === undefined) return 'Undefined';
return Object.prototype.toString.call(o).slice(8, -1);
}
var Person = {
name: "jack",
age: "18",
Address: {
province: "beijing"
},
};
var New = deepClone(Person);
New.name = "tom";
New.Address.province = "shanghai";
console.log(Person.name); //jack
console.log(Person.Address.province); //beijing
console.log(New.name); //tom
console.log(New.Address.province); //shanghai