我可以保留对象的副本,在其创建时在对象内部 [英] Can I preserve a copy of an object, inside that object when its created

查看:96
本文介绍了我可以保留对象的副本,在其创建时在对象内部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

  function student(id,name,marks){
this.id = id;
this.name = name;
this.marks = marks;
}



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

  function student(id,name,marks){
this.id = id;
this.name = name;
this.marks = marks;
this.baseCopy = this;
}

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



1。

解决方案这种可能性使我可以保留一个对象的副本, / div>

因为你已经在使用jQuery,一般的答案是:

  this.baseCopy = $ .extend true,{},this); 

将生成当时存在的任何属性值的深度副本,

- 我确实包含了一些通用的JS代码,但是OP完全改变了这个问题,所以更容易还原只是使用jQuery。这当然会复制直接存在于对象上的任何方法,虽然如果正确写这些方法将在对象的原型。


Can I preserve a copy of an object, inside that object when its created

This is my function which creates a new student object:

function student(id, name, marks){
    this.id = id;
    this.name = name;
    this.marks = marks;
}

I would like to create a copy of the object when it is initialized inside that object: I came up with this:

function student(id, name, marks){
    this.id = id;
    this.name = name;
    this.marks = marks;
    this.baseCopy = this;
}

But the problem is its giving me a infinite loop of copies of current object in baseCopy; ANd also it is automatically updating when ever I update any attributes of my object.

1. How is this possible such that, I can preserve a copy of an object with the initial values, inside that object when its created?

解决方案

Since you're already using jQuery the generic answer is:

this.baseCopy = $.extend(true, {}, this);

will produce a "deep" copy of any property values that exist at the time, without it recursively referring to itself.

NOTE - I did include some generic JS code, but then the OP completely changed the question, so it's simpler to revert back to just using jQuery. This will of course copy any methods that exist directly on the object, although if written properly these methods would be on the object's prototype.

这篇关于我可以保留对象的副本,在其创建时在对象内部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆