@TedZhou
2018-12-10T11:55:14.000000Z
字数 1078
阅读 346
javascript
浅克隆[Plain Clone]:
var obj1 = {foo: "foo", bar: "bar"};
var obj2 = {foo: "foo2", bar: "bar2"};
var copy1 = {...obj1}; // Object {foo: "foo", bar: "bar"}
var copy2 = Object.assign({}, obj); //Object {foo: "foo2", bar: "bar2"}
var copySpread = {...obj1, ...obj2}; //Object {foo: "foo2", bar: "bar2"}
var copyAssign = Object.assign({}, obj2, obj1); //Object {foo: "foo", bar: "bar"}
JSON克隆[Json Clone]
var obj = { a: 0, b: { c: 0 } };
var copy = JSON.parse(JSON.stringify(obj));
深度克隆[Deep Clone]
function deepClone(obj) {
var copy;
// Handle the 3 simple types, and null or undefined
if (null == obj || "object" != typeof obj) return obj;
// Handle Date
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = deepClone(obj[i]);
}
return copy;
}
// Handle Function
if (obj instanceof Function) {
copy = function() {
return obj.apply(this, arguments);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = deepClone(obj[attr]);
}
return copy;
}
throw new Error("Unable to copy obj as type isn't supported " + obj.constructor.name);
}