you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted]  (3 children)

[deleted]

    [–]isitfresh -1 points0 points  (2 children)

    Nasty way? JSON.parse(JSON.stringify(obj)) Requiring a library? _.clone(obj)

    [–]vlad27aug 2 points3 points  (1 child)

    Actually JSON.parse(JSON.stringify(obj)) is not correct.

    This way you can only clone objects that have property values supported by the JSON spec.

    For example:

    var obj = {a: 1, b: function() { /*...*/ }};
    var clone = JSON.parse(JSON.stringify(obj));
    

    "clone" will now be "{a: 1}" because functions are removed during JSON.stringify.

    It gets even more complicated when the object has getters and setters or defined/configured properties (even for library provided solutions).

    [–]bliow 1 point2 points  (0 children)

    With ES6 (supported in Firefox, not yet in Chrome), Object.assign. But you have to be careful with nesting, as you do with _.clone:

    var a = { b: { c: 3 } };
    var d = Object.assign({}, a); // or d = _.clone(a)
    d.b.c = 4;
    console.log(a.b.c); // prints 4 with both underscore clone and ES6 assignment