这是
My Old Question的延续
这是我创建一个新学生对象的函数:
function student(id,name,marks,mob,home){
this.id = id;
this.name = name;
this.marks = marks;
this.contacts = {};
this.contacts.mob = mob;
this.contacts.home = home;
this.toContactDetailsstring = function(){
return this.name +':'+ this.mob +','+ this.home
}
}
我想在该对象内初始化对象时创建该对象的副本:
我想出了这个:
function student(id,'+ this.home
}
this.basecopy = this; //Not sure about this part
}
但问题是它给我一个无限循环的basecopy当前对象的副本;当我更新我的对象的任何属性时,它也会自动更新.
1.这是如何可能的,我可以保留一个具有初始值的对象的副本,在该对象创建时?
2.是否可以不复制功能
3.我很好奇,如果没有硬编码属性名称和使用纯JS,这是否可行
解决方法
非常类似于我在上一个问题上的答案,您可以使用此代码制作对象的副本及其嵌套属性,而不是复制它的功能:
function student(id,'+ this.home
}
// copy the object to basecopy
this.basecopy = clone(this); // "clone" `this.basecopy`
}
function clone(obj){
if(obj == null || typeof(obj) != 'object'){ // If the current parameter is not a object (So has no properties),return it;
return obj;
}
var temp = {};
for(var key in obj){ // Loop through all properties on a object
if(obj.hasOwnProperty(key) && !(obj[key] instanceof Function)){ // Object.prototype fallback. Also,don't copy the property if it's a function.
temp[key] = clone(obj[key]);
}
}
return temp;
}
var s = new student(1,'Jack',[5,7],1234567890,0987654321);
s.marks = s.marks.concat([6,8]); // Jack's gotten 2 new marks.
console.log(s.name + "'s marks were: ",s.basecopy.marks);
// Jack's marks were: [5,7]
console.log(s.name + "'s marks are: ",s.marks);
// Jack's marks are: [5,7,6,8]
console.log(s.basecopy.toContactDetailsstring); // check if the function was copied.
// undefined
console.log(s.basecopy.contacts.mob);
// 1234567890
(我会在深度复制上工作一段时间)
“深层”副本现在应该可以使用了.