2 ms·
It is fundamentally very hard (impossible?) to deep copy everything in JavaScript. References cannot be escaped because they may be hidden in non-introspectable
by dan-robertson 8y ago
It is fundamentally very hard (impossible?) to deep copy everything in JavaScript. References cannot be escaped because they may be hidden in non-introspectable (cruicially, non cloneabel) places. Viz:
function f(){var x = 0; return function(){return x++;};}
var x = {foo:f()};
print(x.foo());
var y = {foo:f()};
print(y.foo());
var z = someDeepCopy(y);
print(z.foo());
print(x.foo());
print(y.foo());
print(z.foo());
If a copy were sufficiently deep then one could expect:
0
0
1
1
1
2
However if it were not deep one would get:
0
0
1
1
2
3
Even if one allows a deep copying of closures then this still might not work as an object which contains two (potentially different) functions closing over the same binding (ie particular instance of a particular variable) may be copied into two functions each closing over their own separate binding.
I think the only good solution to this is to either give up trying to do deep copies or give up immutability and stop caring about deep copies.