Introduction
I have a Class Persons
that contains an array of Person
and functions :
function Persons() {
this.mItems = []; // Array of Objects Person
}
Persons.prototype = {
calculateScores : function() {
// Do some stuff
}
}
The Class Person
has members and functions :
function Person(name) {
this.name = name; // Name of the Person
this.score = 0;
}
Person.prototype = {
calculateScore : function() {
// Do some stuff
}
}
I want that the program does the following things :
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
Question
I want to deep copy an instance of Persons
to completely duplicate the Array of Person
. The Objects Person must be duplicated. The functions of the Objects must be kept.
JQuery.extend()
JQuery.extend(true, {}, persons)
clones the direct members of Persons
but shallow copies the Person
Objects.
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))
clones the Objects but remove the functions.
persons.mItems[0].calculateScore(); // Does not exists !!!
Thank you for your answers.