JS对象的克隆Clone

浅克隆[Plain Clone]:

1
2
3
4
5
6
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]

1
2
var obj = { a: 0, b: { c: 0 } };
var copy = JSON.parse(JSON.stringify(obj));

深度克隆[Deep Clone]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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);
}