Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么嵌套对象不通过引用传递?_Javascript - Fatal编程技术网

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}
谢谢你:)。。。。