简介
我有一个类(class)Persons
包含 Person
的数组和功能:
function Persons() {
this.mItems = []; // Array of Objects Person
}
Persons.prototype = {
calculateScores : function() {
// Do some stuff
}
}
类(class)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
的数组。对象 Person 必须重复。必须保留对象的功能。
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
或其他一些也需要克隆的对象)。
关于javascript - 如何在Javascript中深度复制(克隆)带有数组成员的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31435084/