Cloning the object in JavaScript

This question already has an answer here:

  • What is the most efficient way to deep clone an object in JavaScript? 57 answers

  • The simplest way to clone an object is using the following function:

    function clone(a){var b=function(){};b.prototype=a;return new b;}
    

    This creates a basic copy of the object, do note though that this does not create a deep copy, only a shallow one.


    试试这与jQuery:

    var parent = {};
                    parent["Task name"] = "Task " + ++x;
                    parent["Start time"] = "01/03/2013";
                    parent["End time"] = "01/08/2013";
                    parent["Duration"] = "5 days";
                    parent["Status"] = Math.round(Math.random() * 100);
    var newObj = jQuery.extend(true, {}, parent);
    

    The most basic way is as follows :

    var clone = {};
    for (var k in parent) {
        clone[k] = parent[k];
    }
    

    Works in this case since all values are of primitive types.

    链接地址: http://www.djcxy.com/p/40716.html

    上一篇: C ++

    下一篇: 在JavaScript中克隆对象