JavaScript: How to make a copy of a object?

This question already has an answer here:

  • What is the most efficient way to deep clone an object in JavaScript? 57 answers
  • Cloning the object in JavaScript [duplicate] 3 answers

  • You have to be careful when working with Javascript objects and the equals ( = ) operator. This operator does not create a copy of the object, but only assigns a reference to the original internal object.

    That means that in your case, b does not store the value(s) of a, but after calling

    var b = a;
    

    both a and b point to the same object in memory! Therefore, changing any properties of b also changes them for a (again: they're the same object internally).

    To create a copy of an object you have to manually copy every property of it:

    var a = {};  // create an empty object
    a.prop1 = 1; // set a property of this object
    var b = {};  // create another empty object
    b.prop1 = a.prop1; // copy all properties (in this case: only one) of a to b
    b.test = 1;  // add a new property to b
    alert(a.test); // => undefined, as .test is only defined for b
    a === b; // => false, as a and b are different objects.
    

    An elegant solution to the problem of cloning JS-objects can be found here: How do I correctly clone a JavaScript object?


    In plain JavaScript you could do:

    var copy = JSON.parse(JSON.stringify(myObj));
    

    See: http://jsfiddle.net/kukiwon/AyKdL/


    How about using deep copy pattern like below. This is from "Javascript Patterns" of Stoyan Stefanov.

    function extendDeep(parent, child) {
        var i,
            toStr = Object.prototype.toString,
            astr = "[object Array]";
    
        child = child || {};
    
        for (i in parent) {
            if (parent.hasOwnProperty(i)) {
                if (typeof parent[i] === "object") {
                    child[i] = (toStr.call(parent[i]) === astr) ? [] : {};
                    extendDeep(parent[i], child[i]);
                } else {
                    child[i] = parent[i];
                }
            }
        }
        return child;
    }
    
    链接地址: http://www.djcxy.com/p/6954.html

    上一篇: TypeError:对象不是新的<anonymous>函数

    下一篇: JavaScript:如何制作一个对象的副本?