Can I preserve a copy of an object, inside that object when its created
This is my function which creates a new student object:
function student(id, name, marks){
this.id = id;
this.name = name;
this.marks = marks;
}
I would like to create a copy of the object when it is initialized inside that object: I came up with this:
function student(id, name, marks){
this.id = id;
this.name = name;
this.marks = marks;
this.baseCopy = this;
}
But the problem is its giving me a infinite loop of copies of current object in baseCopy; ANd also it is automatically updating when ever I update any attributes of my object.
1. How is this possible such that, I can preserve a copy of an object with the initial values, inside that object when its created?
Since you're already using jQuery the generic answer is:
this.baseCopy = $.extend(true, {}, this);
will produce a "deep" copy of any property values that exist at the time, without it recursively referring to itself.
NOTE - I did include some generic JS code, but then the OP completely changed the question, so it's simpler to revert back to just using jQuery. This will of course copy any methods that exist directly on the object, although if written properly these methods would be on the object's prototype.
A jQuery-less alternative:
(Just so you know it can also be done without.)
function student(id, name, marks){
this.id = id;
this.name = name;
this.marks = marks;
var tempCopy = {}; // Initialize a temporary variable to copy the student to.
for(key in this){ // Loop through all properties on this (student)
if(this.hasOwnProperty(key)){ // Object.prototype fallback. I personally prefer to keep it in, see Alnitak's comment.
tempCopy[key] = this[key]; // Copy the property
}
}
this.baseCopy = tempCopy; // "Save" the copy to `this.baseCopy`
}
var s = new student(1, 'Jack', [5,7]);
s.marks = s.marks.concat([6,8]); // Jack's gotten 2 new marks.
console.log(s.name + "'s marks were: ", s.baseCopy.marks);
console.log(s.name + "'s marks are: ", s.marks);
// Logs:
// Jack's marks were: [5, 7]
// Jack's marks are: [5, 7, 6, 8]
The advantage of this is that it will automatically copy all properties of the student, without having to "set" them in baseCopy
, manually.
Also, since it doesn't use jQuery, it's a little faster. This could be significant when working with large amounts of data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With