Reputation: 302
Given the following code:
let obj = { data: 1 };
let ref1 = { data: obj };
let ref 2 = [ obj ];
How can I delete obj
is such a way that it's references are also removed? (I mean that ref1.data === null && ref2.length === 0
)
Is it possible?
Upvotes: 1
Views: 2032
Reputation: 7175
You can not delete all references of object. Setting obj=null
will not have impact on its references. You can use delete
keyword to delete properties of object.
let obj = { data: 1 };
let ref1 = { data: obj };
let ref2 = [ obj ];
delete obj; // no effect
console.log(obj.data); // still have 1
console.log(ref1.data); // still have obj value
obj=null;
console.log(obj) //null
console.log(ref1.data) //still have obj value
Upvotes: 0
Reputation: 527
Somewhere inside the javascript execution environment there is some piece of code that is keeping track of references to objects and running memory garbage collection when all the references go out of scope.
You are looking for something similar, except you want to somehow find all active references to a particular object at a particular point in time, and change that reference to null.
I don't think that's possible, unless you want to write your own javascript interpreter.
But perhaps if you back up a level and explain why you want to do this, there is a way to achieve your goal.
Upvotes: 1
Reputation: 3721
You can remove the property from the object:
let obj = {
data: 1
};
let ref1 = {
data: obj
};
let ref2 = [obj];
delete obj.data;
console.log(obj);
console.log(ref1.data);
Upvotes: 0