Search code examples
javascriptlodash

lodas deepClone or deepClone from clone_deep npm returns same instance


What I'm observing now is making me question reality. Of course I'm working with Javasript.

I have following code (clone-deep npm package v 4.0.1)

    let deepCloned = cloneDeep(obj);
    
    if (deepCloned === obj) {
        debugger;
    }

and of course in some cases the debugger is hit. When I change it to lo dashes implementation

    let deepCloned = _.cloneDeep(obj);
    
    if (deepCloned === obj) {
        debugger;
    }

same behavior can be observed. So I have to be missing something really fundamental here. What is it?


Solution

  • from the package page: https://www.npmjs.com/package/clone-deep#heads-up

    Heads up!

    The last argument specifies whether or not to clone instances (objects that are from a custom class or are not created by the Object constructor. This value may be true or the function use for cloning instances.

    When an instanceClone function is provided, it will be invoked to clone objects that are not "plain" objects (as defined by isPlainObjectisPlainObject). If instanceClone is not specified, this library will not attempt to clone non-plain objects, and will simply copy the object reference.

    I do not use that package myself and you did not mention how the "obj" is created so I cannot reproduce your exact problem.