简体   繁体   English

如何在Javascript中克隆整个“对象”?

[英]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. 因为在复制此SquareObject之后,我将不得不更改位于arrayObj的属性,同时仍保留其原始状态的副本。

I've found ways of cloning just the content of arrayObj, but right now that doesn't fully solve my problem. 我已经找到了只克隆arrayObj内容的方法,但是现在还不能完全解决我的问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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