Deep cloning objects defined by JSON.

Xavier MONTILLET xavierm02.net at gmail.com
Sun Jan 29 10:50:29 PST 2012


With your last two implementations, you don't keep cyclic references.

On Sun, Jan 29, 2012 at 7:39 PM, Peter van der Zee <ecma at qfox.nl> wrote:
> On Sun, Jan 29, 2012 at 7:23 PM, David Bruant <bruant.d at gmail.com> wrote:
>> Based on your description, it seems that the definition would be:
>>
>> JSON.clone = function(o){
>>  return JSON.parse(JSON.stringify(o));
>> }
>
> Yes. You can debate whether it should remove properties it can't
> serialize completely, or define them with null. You can also debate
> whether you want to treat objects that don't directly inherit from
> Object as alien (right now that doesn't seem to be the case in Chrome
> at least.
>
> JSON.clone({foo:5}) -> {foo:5}
>
> These are the cases I could (easily) see debatable...
>
> JSON.clone({foo:function(){}}) -> {foo:null} or {}
> function F(){}
> JSON.clone({foo:new F}) -> {foo:{}} or {foo:null} or {}
> var f = new F;
> f.x = 5;
> JSON.clone({foo:f}) -> {foo:{x:5}} or {foo:null} or {}
> F.prototype.x = 5;
> JSON.clone({foo:new F}) -> {foo:{x:5}} or {foo:{}} or {foo:null} or {}
>
> But I guess keeping the same behavior as JSON.stringify for a
> JSON.clone method might be best to keep things consistent. So
> something like Mark's last suggestion, to make the whole thing
> customizable.
>
> - peter
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss


More information about the es-discuss mailing list