5 ms·
Fundamentaly, deep-copy in Javascript is a typed operation and no "generic" deep-copy algorithm is possible--you have to know what meaning the value is supposed
by bcoates 8y ago
Fundamentaly, deep-copy in Javascript is a typed operation and no "generic" deep-copy algorithm is possible--you have to know what meaning the value is supposed to have to copy it.
There's nothing inherently wrong with structured clone, but it's only for JSON-able objects with extensions for circular references and some built in value-like classes. It's also special-cased for safe transmission between Javascript domains so it has a bunch of undesirable behavior for local copies. (no dom, no functions, no symbols, no properties...)
Even primitive types can't be safely copied unless you know what they're going to be used for later, a nodejs file descriptor is just an integer but it's also a reference to an OS resource that can't be duplicated without a syscall.
- amelius 8y ago> Fundamentaly, deep-copy in Javascript is a typed operation and no "generic" deep-copy algorithm is possible--you have to know what meaning the value is supposed to have to copy it. Why? I see no problem if the deep-copy behaves exactly the same as the original, from the perspective of any operation in the Javascript API (except for the === operator).
- bcoates 8y agoExactly the same as the original is a shallow copy. Deep copy roughly means "If I do `dst = deepcopy(src)`, modifying anything in the world I can reach through a reference from dst should have no side effect visible through src" which is a reasonable thing to ask in some special cases (a tree of plain old javascript values, a DOM node) but not reasonable in others (a database connection object, a file descriptor, a user-id) Like, what should a deep copy function do if it reaches a reference to the global object? or a function that closes over some references in the object being copied? The answer is always "it depends on what the object will be used for later and what specific behavior you want"
- deleted 8y ago[deleted]
- kccqzy 8y agoThe === operator is a coercion-free equality operator. It's not an object identity comparison operator.
- XCSme 8y agoBut for `Objects` (not primitves) it is the identity comparison operator, right?
- kccqzy 8y agoI wasn't aware of that. I thought ES2015 added Object.is() for this purpose: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- AgentME 8y agoThe main difference between === and Object.is() is that === treats +0 and -0 as equivalent, despite the fact that some math operations treat them differently. I think they added Object.is() because it was awkwardly difficult to make code tell the difference between +0 and -0.
- scottmf 8y agoYes
- ZenPsycho 8y agotechnically for primatives too, since they are interned, immutable and their value is their identity?