关于此主题的问题有数百万,但我找不到这种情况的解释:
const obj = { nObj: {a: 1}};
const obj2 = obj.nObj; // the value of obj2 is an object, not a primitive
obj.nObj = {b: 2};
console.log(obj2) // outputs {a: 1}
为什么会这样?
答案 0 :(得分:3)
请注意,值是通过引用而不是键传递的
以下是注释中的解释。
// There are 2 references here one being referenced by obj and the other is by obj.nObj
const obj = { nObj: {a: 1}};
// obj2 also starts pointing to the same reference as obj.nObj
const obj2 = obj.nObj; // the value of obj2 is an object, not a primitive
// obj.nObj now points to a different reference
obj.nObj = {b: 2};
// obj2 continues to hold the original reference, hence, remains unchanged.
console.log(obj2) // outputs {a: 1}