Deep cloning objects defined by JSON.

Peter van der Zee ecma at
Sun Jan 29 10:39:31 PST 2012

On Sun, Jan 29, 2012 at 7:23 PM, David Bruant <bruant.d at> 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

- peter

More information about the es-discuss mailing list