Javascript 为什么嵌套对象不通过引用传递?
关于这个话题有数百万个问题,但我找不到对这种情况的解释:Javascript 为什么嵌套对象不通过引用传递?,javascript,Javascript,关于这个话题有数百万个问题,但我找不到对这种情况的解释: 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} 为什么会发生这种情况?请注意,值是通过引用传递的,而不是键 以下是评论中的解释 // There are 2 refe
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}
为什么会发生这种情况?请注意,值是通过引用传递的,而不是键 以下是评论中的解释
// 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}
谢谢你:)。。。。