So, for this problem, you have to understand what is the shallow
copy and deep
copy.
Shallow copy is a bit-wise copy of an object which makes a new object by copying the memory address of the original object. That is, it makes a new object by which memory addresses are the same as the original object.
Deep copy, copies all the fields with dynamically allocated memory. That is, every value of the copied object gets a new memory address rather than the original object.
Now, what a spread operator does? It deep copies the data if it is not nested. For nested data, it deeply copies the topmost data and shallow copies of the nested data.
In your example,
const oldObj = {a: {b: 10}};
const newObj = {...oldObj};
It deep copy the top level data, i.e. it gives the property a
, a new memory address, but it shallow copy the nested object i.e. {b: 10}
which is still now referring to the original oldObj
's memory location.
If you don't believe me check the example,
const oldObj = {a: {b: 10}, c: 2};
const newObj = {...oldObj};
oldObj.a.b = 2; // It also changes the newObj `b` value as `newObj` and `oldObj`'s `b` property allocates the same memory address.
oldObj.c = 5; // It changes the oldObj `c` but untouched at the newObj
console.log('oldObj:', oldObj);
console.log('newObj:', newObj);
.as-console-wrapper {min-height: 100%!important; top: 0;}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…