gpt4 book ai didi

javascript - 我可以在对象创建时保留该对象的副本吗 - 续 :

转载 作者:数据小太阳 更新时间:2023-10-29 05:13:07 28 4
gpt4 key购买 nike

这是 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, 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
}
this.baseCopy = this; //Not sure about this part
}

但问题是它在 baseCopy 中给了我当前对象副本的无限循环;并且当我更新对象的任何属性时它也会自动更新。

<强>1。这怎么可能使得我可以在创建对象时在该对象内部保留具有初始值的对象副本?

<强>2。是否可以不复制函数

<强>3。我很好奇,如果不对属性名称进行硬编码并使用纯 JS,这是否可行

最佳答案

与我对您上一个问题的回答非常相似,您可以使用此代码复制对象及其嵌套属性,而不是复制它的函数:

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
}

// 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

(我将处理深拷贝一秒钟)

“深层”副本现在应该可以工作了。

关于javascript - 我可以在对象创建时保留该对象的副本吗 - 续 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13969104/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com