简体   繁体   中英

How to clone an entire “object” in Javascript?

I've tried lots of solution that I've found in here, but until now any of them really solved my problem.

Let's say that I have a function like this:

    var SquareObject = function(id, x, y, text, rectClass, textClass){
      var arrayObj = {
        "id": null,

        "shape": "rect",

        "label": null,

        "rect": {
          "class": null,
          "x": null,
          "y": null,
          ...
        },

        "text": {
          "class": null,
          "x": null,
          "y": null,
          ...
        }

        function initArrayObj(){
          ...
        }

        function anotherFunction(){
          ...
        }
    }

How can I copy everything, including the methods? Because after I make a copy of this SquareObject I'll have to change the properties located at arrayObj, while still maintaining a copy of its original state.

I've found ways of cloning just the content of arrayObj, but right now that doesn't fully solve my problem.

Thanks!

var copyObj = arrayObj.constructor();
for (var attr in arrayObj) {
    if (arrayObj.hasOwnProperty(attr)) {
        copyObj[attr] = arrayObj[attr];
    }
}

If you want to copy the function as it is

var obj= Object.assign(SquareObject)
console.log(obj)

If you want to copy a constructor then

Person(){
  this.age=20;
  this.name='ignatius';
  this.display = function(){
    console.log(`Name : ${this.name}  ${this.age}.`);
 }
}

var copy = Object.assign(Person);
var obj = new Person();

console.log(obj.name)// 'ignatius'

This also works for objects.

var a= {
          name: 'ignatius',
          age: 2
  }

var copy = Object.assign(a)

console.log(a.name ) // ignatius

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM