克隆
普通克隆
//普通克隆
var origin = {
name:"xiaoli",
age:18,
say:function(){
console.log(this.name);
}
}
var target = {}
function clone(origin,target){
var target = target || {};
for(var prop in origin){
target[prop] = origin[prop];
}
return target;
}
clone(origin,target);
深度克隆
/*
遍歷對(duì)象 for in
1.判斷是不是原始值 typeof() object
2.判斷時(shí)數(shù)組還是對(duì)象instanceof toString constructor
3.建立相應(yīng)的數(shù)組或?qū)ο?遞歸....
if(typeof(origin[prop]))
*/
var obj = {
name: "abc",
age: 123,
card: ["visa", "unionpay"],
wife: {
name: "bcd",
son: {
name: "erzi"
}
}
}
var obj1 = {};
function deepClone(origin, target) {
var target = target || {},
toStr = Object.prototype.toString,
arrStr = "[object Array]",
objStr = "[object Object]";
for (var prop in origin) {
if (origin.hasOwnProperty(prop)) {
if (origin[prop] !== "null" && typeof (origin[prop]) == "object") {
//是的話代表引用值
if (toStr.call(origin[prop] == arrStr)) {
target[prop] = [];
} else {
target[prop] = {};
}
deepClone(origin[prop],target[prop]);
} else {
target[prop] = origin[prop];
}
}
}
return target;
}
deepClone(obj, obj1);
// console.log(deepClone(obj));
console.log(obj1);