On Wed, Nov 30, 2011 at 3:37 PM, Jarek Foksa <[email protected]> wrote:

> How can I create an exact copy of object? Is there a simple technique
> that would allow me to preserve:
> - non-enumerable properties
> - getter and setter methods
> - entire prototype chain
> - circular references (if any)
>
> There is Object.create() in ES5 which copies nicely the whole
> prototype chain, but I'm not sure how to copy properties that belong
> to the top level object. Using "for in" loop like below would skip
> non-enumerable properties


Object.getOwnPropertyNames is your friend.


> and would copy the values returned by
> getters (instead of getter functions itself).
>

Hmm...good question. If there's not an introspection API for this there
really should be.

Also, you didn't list host objects, but these are important and impossible.
And you didn't really note what this for was, but another thing that'll
give you grief is the closure context of functions. The long and short of
it is it'll always be impossible to do *completely*.


>
> function copy(refObject) {
>  var newObject = Object.create(Object.getPrototypeOf(refObject));
>  var property;
>
>  for (property in refObject) {
>    if (refObject.hasOwnProperty(property)) {
>      newObject[property] = refObject[property];
>    }
>  }
>
>  return newObject;
> }
>
> --
> To view archived discussions from the original JSMentors Mailman list:
> http://www.mail-archive.com/[email protected]/
>
> To search via a non-Google archive, visit here:
> http://www.mail-archive.com/[email protected]/
>
> To unsubscribe from this group, send email to
> [email protected]
>

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to