Deep cloning objects defined by JSON.

Peter van der Zee ecma at qfox.nl
Sun Jan 29 10:05:59 PST 2012


Why can't we define a JSON.clone() or .deepClone() which would only
clone properties that are primitives, object or array. If they are
(instanceof) array, copy index properties and length value and create
new array with that information. If object, create new object and copy
all properties with the same restrictions as before.

I suppose another discussion is whether you'd want/need to copy
property attributes as well. For me, for at least JSON.clone, I would
be happy with just a clone of the primitive value of a property.

In other words, I think a JSON.clone would work as if the structure
was first serialized to a string. The serialization would drop any
value or property that's not primitive, object or array. Objects and
arrays are serialized to [] and {} notation. For arrays, only index
properties are copied (so not even length or other properties). The
resulting string would then be deserialized by JSON.parse. Of course
the serialization doesn't need to happen internally, but I think hope
that makes it clear what I mean (drops all weird stuff from structures
like getters, setters and attributes).

By putting such a method on JSON, you leave the way open for whatever
clone should be on Object and still have an intuitive feeling for what
JSON.clone would probably do (opposed to Object.clone).

Cloning functions is a dangerous sport anyways due to closures, but I
don't think anyone would expect JSON.clone to clone functions too.

- peter

On Tue, Jan 24, 2012 at 7:46 PM, Rick Waldron <waldron.rick at gmail.com> wrote:
> non-recursive, deep clone by John-David Dalton:
>
> https://github.com/bestiejs/benchmark.js/blob/master/benchmark.js#L1001-1161
>
>
> Rick
>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>


More information about the es-discuss mailing list