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?
So
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.