我查看了js文档,并且在研究它在object.assign()中提到的文档时 如果源值是对对象的引用,则它只复制该引用值.
在我的下面的代码片段中,一个改变了原始对象,而另一个不改变
var objA = {
a: 1,
b: {
c: 2,
d: {
e: 3,
},
},
}
var objC = { t: 1 };
//why this works i.e adds a to objEmpty
// var objEmpty = Object.assign({}, { objC }); //this would add a prop to the objEmpty object
//this doesnt work i.e doesnt add a to objEmpty
var objEmpty = Object.assign({}, objC); //this will not
objC.a = 3;
console.log(objC);
console.log(objEmpty);
我正在通过try 不同的场景来弄清楚事情到底是如何运作的,我相信这是与引用有关的事情,但如何运作呢?
文档中的另一个例子
const obj2 = Object.assign({}, obj1);
console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}
obj1.a = 1;
console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 0}}
console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}
obj2.a = 2;
console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 0}}
console.log(JSON.stringify(obj2)); // { "a": 2, "b": { "c": 0}}
obj2.b.c = 3;
console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 3}}
console.log(JSON.stringify(obj2)); // { "a": 2, "b": { "c": 3}}```
why does js behave this way? why the 3 got changed but the other didn't?
Thanks in advance :)