Cloning an Object in Node.js

后端 未结 21 1916
情书的邮戳
情书的邮戳 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:20

    You can prototype object and then call object instance every time you want to use and change object:

    function object () {
      this.x = 5;
      this.y = 5;
    }
    var obj1 = new object();
    var obj2 = new object();
    obj2.x = 6;
    console.log(obj1.x); //logs 5
    

    You can also pass arguments to object constructor

    function object (x, y) {
       this.x = x;
       this.y = y;
    }
    var obj1 = new object(5, 5);
    var obj2 = new object(6, 6);
    console.log(obj1.x); //logs 5
    console.log(obj2.x); //logs 6
    

    Hope this is helpful.

提交回复
热议问题