2016-05-30

聚沙

浅复制和深复制

关于 Date 对象

1
2
3
4
5
6
7
// What works
var original = new Date();
var copy = new Date(original);

// What doesn't work
copy = original; // It should work, but it passes by reference so changes to copy also affect original
copy = jQuery.extend(true, {}, original); // Passes a useless object
1
2
3
Date.prototype.clone = function () {
  return new Date(this.getTime());
}

简单的深复制实现:

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
function clone(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] = clone(obj[i]);
        }
        return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
        copy = {};
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
        }
        return copy;
    }

    throw new Error("Unable to copy obj! Its type isn't supported.");
}

https://gist.github.com/RobFreiburger/2166022

http://stackoverflow.com/questions/1090815/how-to-clone-a-date-object-in-javascript

http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object

http://www.cnblogs.com/rubylouvre/archive/2010/03/26/1696600.html

http://jerryzou.com/posts/dive-into-deep-clone-in-javascript/

https://www.zhihu.com/question/23031215

MORE

Comments