Search code examples
javascriptnode.jsdeep-copy

The object copy received via structuredClone() is not equal to the original


I try creating a copy of an object with structuredClone() and then compare it to the original.

const util = require('util');

function A() {}
let obj = {
    key: new A()
};
let copy = structuredClone(obj);
console.log(util.isDeepStrictEqual(obj, copy));

I expect true, but received false.

Could you explain the reason?


Solution

  • The reason is structuredClone cannot clone classes or functions, so your A {} becomes {} in the cloned object.

    Example:

    const util = require('util');
    
    function A(){ this.property = 8}
    let obj = {
        key: new A()
    };
    
    let copy = structuredClone(obj);
    console.log("Obj is:", obj)
    console.log("Copy is:", copy)
    

    That shows:

    Obj is: { key: A { property: 8 } }
    Copy is: { key: { property: 8 } }
    

    As you can see, the copy is no more an A instance... is a Plain Javascript Object