The es6 assign object is shallow copied, and the attribute value of the target object remains unchanged.

topic description

es6 assign object is shallowly copied, and the attribute value of the target object does not change.

sources of topics and their own ideas

after learning es6 assign, I know it is a shallow copy, but there is a strange phenomenon in practice

related codes

/ / Please paste the code text below (do not replace the code with pictures)

const obj1 = {a: {b: 1}, c:3};
const obj2 = Object.assign({}, obj1);

obj1.a.b = 2;
obj1.c=8

console.log(obj2); // {a: {b: 2}, c:3}

Why has the value of c not changed? Isn"t a shallow copy a reference to a copy?

Jun.12,2022

shallow copy only clones the data of the first layer. For deep cloning, you need to implement
https://blog.csdn.net/qq_3010...

.
var deepclone = function(a,b){
    var a = a || {};
    for(var k in b){
        if(b.hasOwnProperty(k))
            a[k] = Object.prototype.toString.call(b[k])=='[object Object]'? 
         deepclone(a[k],b[k]):b[k];
    }
    return a;
}

this feels like you have the wrong understanding of the concept of shallow copy.
shallow copy refers to the outermost layer of the copy, so the value of c is a clone, and the c in obj1 and obj2 points to different


assign only copies the outermost layer, because the an event reference type, so the value changes after the copy, c is the value type, so the value does not change. "copy only the outermost layer" is the key point


so it's called copying

.
Menu