I initially started this thread to ask how this is possible, since it was driving me crazy, but I found a solution so I'm now writing it to share it.
Basically, when wanting to create a copy of an object and want to seclude it from its origin, to use it for tests or whatever, it can't be done by directly assigning the origin to the target.
So this:
will always also change the value of origin.prop.
I tried doing this in about a billion ways. The solution is quite simple and is called "deep clone using JSON"
This seems to copy everything over to the target object, and remove all references between them.
I know this might be common knowledge, but it wasn't to me, so I'm sharing it for all that might be like me ^_^
Basically, when wanting to create a copy of an object and want to seclude it from its origin, to use it for tests or whatever, it can't be done by directly assigning the origin to the target.
So this:
JavaScript:
target = origin;
target.prop++
I tried doing this in about a billion ways. The solution is quite simple and is called "deep clone using JSON"
JavaScript:
target = JSON.parse(JSON.stringify(origin))
This seems to copy everything over to the target object, and remove all references between them.
I know this might be common knowledge, but it wasn't to me, so I'm sharing it for all that might be like me ^_^