浅拷贝
function shallowCopy(target) {
let newObj = {};
for(let k in target) {
if(target.hasOwnProperty(k)) {
newObj[k] = target[k];
}
}
return newObj;
}
深拷贝
function type(target) {
return Object.prototype.toString.call(target).slice(8,-1);
}
function deepCopy(target) {
if(type(target) == 'Function') {
return new Function("return " + target.toString())();
}else if(target === null || (typeof target !== 'object')) {
return target;
}else {
let k, targetObj = (type(target)==='Array') ? [] : {}, value;
for(k in target) {
value = target[k];
if(value === target){
continue;
}
if (type(value)==='Array' || type(value)==='Object') {
targetObj[k] = deepCopy(value);
} else if (type(value)==='Function') {
targetObj[k] = new Function("return " + value.toString())();
} else {
targetObj[k] = value;
}
}
}
return targetObj;
}