[英]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(true, {}, persons)
克隆的直接成員Persons
而淺拷貝的Person
對象。
console.log(persons.mItems[0].name); // Mick : Where is John ?!
console.log(clonedPersons.mItems[0].name); // Mick
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
或一些其他需要克隆的對象)。
您可以使用[].map
和Object.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.