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

Akh*_*ran 6 javascript object

这是我的旧问题的延续

这是我创建一个新学生对象的函数:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

我想在对象内部初始化时创建对象的副本:我想出了这个:

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
}
Run Code Online (Sandbox Code Playgroud)

但问题是它给我一个无限循环的baseCopy当前对象的副本; 当我更新我的对象的任何属性时,它也会自动更新.

1.这是如何可能的,我可以保留一个具有初始值的对象的副本,在该对象创建时?

2.是否可以不复制功能

3.我很好奇,如果没有硬编码属性名称和使用纯JS,这是否可行

Cer*_*rus 3

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

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
Run Code Online (Sandbox Code Playgroud)

(我将研究一下深层副本)

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