I’m trying to understand the true nature of the prototype pattern by looking at how it presents in radically different programming languages.¹
So I decided to look up at JavaScript, as one of the several non-compiled languages around.
And that’s how I refreshed something that I had known in the past, i.e. that foo = bar
in JavaScript is a shallow copy (assuming bar
is an object), thus concluding that JavaScript too does need a way of cloning objects, where cloning means deep copying. So I searched for that and bumped into the developer.mozilla.org/ page on “Deep copy”, where I read that
many JavaScript objects are not serializable at all […] So there’s no way to make deep copies of such objects.
[…] And calling
structuredClone()
to clone a non-serializable object will fail in the same way that callingJSON.stringify()
to serialize it will fail.
from which I’d conclude that there is absolutely no one-size-fits-all solution for deep copying in JavaScript.
Is that indeed the case?
(¹) Coming from C++, I looked at that first, and came to the conclusion that the prototype pattern is after all just the solution to the problem of (deep) cloning a polymorphic object, all the rest that is usually presented with the prototype design pattern being just convient stuff one might want to do as well (a factory, a store of common prototypes, and so on).