Creating a new object, not a reference

This question already has an answer here:

  • What is the most efficient way to deep clone an object in JavaScript? 57 answers
  • How do I correctly clone a JavaScript object? 54 answers

  • 最简单的版本是使用JSON.parse/stringify ,最快的就是使用一个普通的克隆方法:

    /* simplest */
    var clone = JSON.parse(JSON.stringify(obj));
    
    /* fastest */
    function clone(obj) {
        if (obj == null ||typeof obj != "object") return obj;
        var copy = obj.constructor();
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
        }
        return copy;
    }
    var clone2 = clone(obj);
    

    You could write a deep clone Method, which copies every value of every property of your Object to a new one.

    Note i extend Object.prototype to avoid type checking and for simplicities sake, this could be changed, if you feel unpleasent with it

    Object.defineProperty(Object.prototype, "clone", {
        enumerable : false,
        value: function(deep) {
        deep |= 0;      
        var type = typeof this;
        if (type !== "object") {
            return this.valueOf();
        }
    
        var clone = {};
        if (0 === deep) {
            for (var prop in this) {
                clone[prop] = this[prop];
            }
        } else {
            for (var prop in this) {
                if ( typeof this[prop] !== "undefined" && this[prop] !== null)
                    clone[prop] = ( typeof this[prop] !== "object" ? this[prop] : this[prop].clone(deep - 1));
                else
                    clone[prop] = "";
            }
        }
        return clone;
      }
    });
    
    Object.defineProperty(Array.prototype, "clone", {
        enumerable : false,
        value:function(deep) {
        deep |= 0;
        var clone = [];
            if (0 === deep)
                clone = this.concat();
            else
                this.forEach(function(e) {
                    if ( typeof e !== "undefined" && e !== null)
                        clone.push(( typeof e !== "object" ? e : e.clone(deep - 1)));
                    else
                        clone.push("");
                });
        return clone;
      }
    });
    

    Example output and a Demo

    var first = {
      var1:0,
      var2:0
      var3:0
    };
    var second = first.clone(Infinity);
    first.var1++;
    console.log (first.var1,second.var1,second); //1 , 0
    

    To apply this to your code, you just have to clone the Object app.Defaults = app.Variables.clone()

    The first argument is the level of deepness. If omitted, only the first level is cloned, which would be enough in this case.

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

    上一篇: 是否有更好的方式在C#中创建深层和浅层克隆?

    下一篇: 创建一个新对象,而不是引用