Home > Blockchain >  Objects not supported by structuredClone
Objects not supported by structuredClone

Time:01-29

I've been using structuredClone for deep cloning, instead of the cumbersome JSON.parse(JSON.stringify(foo)). However, in the list of supported types, MDN says:

  • Object: but only plain objects (e.g. from object literals).

I'm not sure what would be a non-plain object, an object instantiated by a class? It makes little sense, because structuredClone seems to work on those as well.

In short: what kind of objects are not supported by structuredClone?

CodePudding user response:

I'm not sure what would be a non-plain object, an object instantiated by a class?

Correct. Objects instantiated by a class can be cloned, but they'll be plain objects in the cloned version, so information may be lost.

class X {
    prop = 1
    static staticProp = 2
    method() { return 3 }
}

const x = new X()
const clone = structuredClone(x)

console.log(clone) // { prop: 1 }
console.log(clone instanceof X) // false
console.log(clone.constructor.name) // Object
console.log(clone.constructor.staticProp) // undefined
console.log(clone.method()) // Uncaught TypeError: clone.method is not a function

  • Related