JQuery-less alternative:
(Just to let you know that this 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 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 gotten 2 new marks. console.log(s.name + " marks were: ", s.baseCopy.marks); console.log(s.name + " marks are: ", s.marks); // Logs: // Jack marks were: [5, 7] // Jack marks are: [5, 7, 6, 8]
The advantage of this is that it will automatically copy all the studentโs properties without having to manually set them in baseCopy .
Also, since it does not use jQuery, it works a little faster. This can be significant when dealing with large amounts of data.
Cerbrus
source share