在对象中引用对象 Javascript 混乱
Referencing Object within Object Javascript Confusion
我试图在一个对象中创建一个对象的引用,而不是创建它的一个副本。我对参考与复制感到困惑。让我困惑的是:
let master = {}
master['SomeObject'] = {a:"Something",b:"something"}
let subMaster = master['SomeObject']
subMaster['Test'] = true
console.log(master['SomeObject']['Test'])
//this WORKS as expected updating the original object
delete master['SomeObject']
console.log(subMaster)
//still shows content, and can continue to be manipulated? Shouldnt it show undefined?
为什么删除原始对象后引用仍然有效?如果我误解了引用,我怎样才能确保删除原始对象以便所有引用都不再有效?我可能遗漏了一些基本的东西,感谢任何人的帮助!
delete
不会从内存中物理删除对象。它只会从 master
中删除 属性。由于您仍在引用变量中的对象,并且您的变量没有超出范围,因此该对象仍驻留在内存中。
根据 MDN:
The JavaScript delete
operator removes a property from an object
我试图在一个对象中创建一个对象的引用,而不是创建它的一个副本。我对参考与复制感到困惑。让我困惑的是:
let master = {}
master['SomeObject'] = {a:"Something",b:"something"}
let subMaster = master['SomeObject']
subMaster['Test'] = true
console.log(master['SomeObject']['Test'])
//this WORKS as expected updating the original object
delete master['SomeObject']
console.log(subMaster)
//still shows content, and can continue to be manipulated? Shouldnt it show undefined?
为什么删除原始对象后引用仍然有效?如果我误解了引用,我怎样才能确保删除原始对象以便所有引用都不再有效?我可能遗漏了一些基本的东西,感谢任何人的帮助!
delete
不会从内存中物理删除对象。它只会从 master
中删除 属性。由于您仍在引用变量中的对象,并且您的变量没有超出范围,因此该对象仍驻留在内存中。
根据 MDN:
The JavaScript
delete
operator removes a property from an object