Cloning an Object in Node.js

后端 未结 21 1927
情书的邮戳
情书的邮戳 2020-11-28 02:03

What is the best way to clone an object in node.js

e.g. I want to avoid the situation where:

var obj1 = {x: 5, y:5};
var obj2 = obj1;
obj2.x = 6;
con         


        
21条回答
  •  爱一瞬间的悲伤
    2020-11-28 02:27

    Looking for a true clone option, I stumbled across ridcully's link to here:

    http://my.opera.com/GreyWyvern/blog/show.dml/1725165

    I modified the solution on that page so that the function attached to the Object prototype is not enumerable. Here is my result:

    Object.defineProperty(Object.prototype, 'clone', {
        enumerable: false,
        value: function() {
            var newObj = (this instanceof Array) ? [] : {};
            for (i in this) {
            if (i == 'clone') continue;
                if (this[i] && typeof this[i] == "object") {
                    newObj[i] = this[i].clone();
                } else newObj[i] = this[i]
            } return newObj;
        }
    });
    

    Hopefully this helps someone else as well. Note that there are some caveats... particularly with properties named "clone". This works well for me. I don't take any credit for writing it. Again, I only changed how it was being defined.

提交回复
热议问题