簡體   English   中英

如何使用Java中的數組成員深度復制(克隆)對象?

[英]How to deep copy (clone) an object with array members in Javascript?

介紹

我有一類Persons ,其中包含的陣列Person及功能:

function Persons() {
  this.mItems = []; // Array of Objects Person
}

Persons.prototype = {
  calculateScores : function() {
    // Do some stuff
  }
}

班級Person具有成員和職能:

function Person(name) {
  this.name = name; // Name of the Person
  this.score = 0;
}

Person.prototype = {
  calculateScore : function() {
    // Do some stuff
  }
}

我希望程序執行以下操作:

var persons = new Persons();
var person0 = new Person("John");
var person1 = new Person("Sam");
persons.mItems.push(person0);
persons.mItems.push(person1);

// Completely clone the original Objects
clonedPersons = persons.clone(); // I am looking for a clone() function

// Modify an item in the cloned Objects
clonedPersons.mItems[0].name = "Mick";

// Check that the original Objects have not been modified
console.log(persons.mItems[0].name); // John : Not modified
console.log(clonedPersons.mItems[0].name); // Mick

我想復制一個Persons實例以完全復制Person Array。 對象人必須重復。 對象的功能必須保留。

JQuery.extend()

JQuery.extend(true, {}, persons)克隆的直接成員Persons而淺拷貝的Person對象。

console.log(persons.mItems[0].name); // Mick : Where is John ?!
console.log(clonedPersons.mItems[0].name); // Mick

JSON.parse(json.stringify())

clonedPersons = JSON.parse(json.stringify(persons))克隆對象,但刪除函數。

persons.mItems[0].calculateScore(); // Does not exists !!!

謝謝您的回答。

如果要處理自定義類,則將要實現自定義clone方法。 通常,在這種情況下,我將有2個單獨的clone函數,一個在Person模型上,另一個在Persons集合上。

Persons.prototype = {
  clone: function() {
    var clone = new Persons();
    clone.mItems = this.mItems.map(function(person) {
        return person.clone();
    });
    return clone;
  }
}

Person.prototype = {
  clone: function() {
    var clone = new Person(this.name);
    clone.score = this.score;
    return clone;
  }
}

這種方法的優點是它可以將關注點分離開Person類不必知道如何克隆單個Person ,而只需知道Person公開了一個clone方法。 如果Person添加了應保留在克隆中的新屬性,則僅需更改Person

在這種情況下,使用通用clone方法(例如來自jQuery或Underscore的方法)通常是一種反模式。 他們最終會克隆您不想要的東西,或者丟失您要做的事情(例如,一個Person最終可能擁有一個Address或一些其他需要克隆的對象)。

您可以使用[].mapObject.assign

Persons.prototype.clone = function() {
   var clone = new Persons();
   clone.mItems = this.mItems.map(function(person) {
     return Object.assign(new Person, person);
   });
   return clone;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM