0

I am trying to create a reference to an object within an object, rather than creating a copy of it. I'm confused about reference vs. copy. What confuses me:

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?

Why does the reference still work even after deleting the original object? If I'm misunderstanding references, how can I make sure the original object is deleted so all references no longer work? I'm probably missing something fundamental and I appreciate anyones help!

1 Answer 1

2

delete does not physically delete the object from memory. It only removes that property from master. Since you are still referencing the object from your variable, and your variable has not fallen out of scope, the object still resides in memory.

Per MDN:

The JavaScript delete operator removes a property from an object

Sign up to request clarification or add additional context in comments.

6 Comments

thank you, so if I were to add subMaster = undefined would that allow the original object to be removed from memory?
also, if its based on all existing references, what if an object has a method that uses the 'this' reference to access internal properties? Would that prevent the object from being removed from memory?
@sychordCoder for your first question, no it would not. All referencing variables/properties must fall out of scope or be set to undefined. If you set EVERY reference to that object to undefined or null or some other object, only then it will be removed from memory.
@sychordCoder I'm not exactly sure what your asking in the second question
is there a programmatic way to remove all references to an object or do I need to just go through and set them all to null? For the second part, if an object has a method let obj = {a:something,method(){return this.a}} would the 'this' reference within the method prevent it from being removed?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.