5 ms·
Not cloning instances of classes properly is a surprise. Is there a particular reason for that?
by twic 3y ago
Not cloning instances of classes properly is a surprise. Is there a particular reason for that?
- KTibow 3y agoClasses have way more complex state that could be unpredictable
- jwalton 3y agoOn the one hand, you’d think the copy would just have a prototype that points to the same as the original’s prototype, and that would make this all work out. I’m surprised that’s not what happens since in 99% of cases it would be fine. On the other hand, when you consider #privateMembers, you realize cloning a class in JS is basically impossible (and adding them to the language was probably a horrible mistake).
- eyelidlessness 3y agostructuredClone is a standard library implementation of the structured clone algorithm, which was originally mainly designed for passing data between realms (eg between threads). Prototype chains are not preserved across realms, so it makes sense that the algorithm wouldn’t either. The accommodation for native/host types is possible because they’re implemented in each realm by the runtime, but user-defined classes don’t have that benefit.