JavaScript 对象克隆

JavaScript 对象克隆分为浅克隆和深克隆。

浅克隆

function clone (obj) {
var newObj = new Object();
for (var key in obj) {
newObj[key] = obj[key];
}
return newObj;
}

深克隆

function cloneDeep (obj) {
if ( !(obj instanceof Object) || (obj instanceof Array) ) {
return obj;
}
var newObj = new Object();
for (var key in obj) {
newObj[key] = cloneDeep(obj[key]);
}
return newObj;
}