为什么嵌套对象没有通过引用传递?

时间:2018-09-26 11:40:20

标签: 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}

为什么会这样?

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}