一个没有 jQuery 的替代方案:(
你知道它也可以不用。)
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]
这样做的好处是它会自动复制学生的所有属性,而不必baseCopy
手动“设置”它们。
此外,由于它不使用 jQuery,因此速度更快。在处理大量数据时,这可能很重要。