gpt4 book ai didi

javascript - 为什么嵌套对象不通过引用传递?

转载 作者:行者123 更新时间:2023-11-29 18:47:59 25 4
gpt4 key购买 nike

关于这个主题有数百万个问题,但我找不到对这种情况的解释:

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}

关于javascript - 为什么嵌套对象不通过引用传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52516897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com