search

Home  >  Q&A  >  body text

javascript - Problems with shallow copy in js.

Looking at this piece of code today, talking about shallow copy

/* ================ 浅拷贝 ================ */
function simpleClone(initalObj) {
    var obj = {};
    for ( var i in initalObj) {
        obj[i] = initalObj[i];
    }
    return obj;
}

/* ================ 客户端调用 ================ */
var obj = {
    a: "hello",
    b: {
        a: "world",
        b: 21
    },
    c: ["Bob", "Tom", "Jenny"],
    d: function() {
        alert("hello world");
    }
}
var cloneObj = simpleClone(obj); // 对象拷贝

console.log(cloneObj.b); // {a: "world", b: 21}
console.log(cloneObj.c); // ["Bob", "Tom", "Jenny"]
console.log(cloneObj.d); // function() { alert("hello world"); }

// 修改拷贝后的对象
cloneObj.b.a = "changed";
cloneObj.c = [1, 2, 3];
cloneObj.d = function() { alert("changed"); };

console.log(obj.b); // {a: "changed", b: 21} // // 原对象所引用的对象被修改了

console.log(obj.c); // ["Bob", "Tom", "Jenny"] // 原对象所引用的对象未被修改
console.log(obj.d); // function() { alert("hello world"); } // 原对象所引用的函数未被修改

1. Logically speaking, shallow copy should not only copy the reference of the object, not the object itself, then both obj.c and obj.d should be modified?

2. var cloneObj=obj, does it count as a shallow copy? How to understand it?

世界只因有你世界只因有你2783 days ago516

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-05-19 10:20:55

    var cloneObj=obj // 这才是浅拷贝,改变这里会联动改变
    // 这个方法不是浅拷贝,是一级深拷贝,二级拷贝是浅拷贝,因为obj[i] = initalObj[i];就相当于你的var cloneObj=obj 。
    function simpleClone(initalObj) {
        var obj = {};
        for ( var i in initalObj) {
            obj[i] = initalObj[i]; ////////注意这里  除非你递归赋值
        }
        return obj;
    }
    

    So

    cloneObj.a = "changed"; // obj不变
    cloneObj.b.a = "changed"; // obj改变
    

    reply
    0
  • 高洛峰

    高洛峰2017-05-19 10:20:55

    1. The variable storing the object can be simply understood as an address, through which other child elements can be obtained. 2. Shallow copy of an object refers to creating a new object and copying the values ​​of its sub-elements in sequence. 3. Therefore, although the sub-element values ​​of the copied objects are the same, they are not equal when compared because the addresses where they store sub-element variables are different. 4. Your second method is direct assignment of addresses. No new variables are generated, or no new addresses for creating subelements are generated. This is not called copying.

    reply
    0
  • Cancelreply