stinkycheeseman
stinkycheeseman

Reputation: 45787

Can an object be garbage collected if a reference to one of it's members still exists?

In Javascript, it is my understanding that items are garbage collected when no references to them exist on the page.

var obj = {
   arr: [1,2,3]
};
var arr = obj.arr;
obj = "hello";

In the above code, I have replaced my reference to the initial obj object. I no longer have any references to that object. However, I do have a reference to an array that was on that object. Is the object kept around until arr is unreferenced? Or can it be garbage collected?

Upvotes: 2

Views: 112

Answers (1)

Pointy
Pointy

Reputation: 413826

The object that was the value of "obj" can be collected, but it's a separate object than the object (the array) that's the value of "arr". That one won't be collected.

An object can be collected independently of objects referenced by its properties.

(Strictly speaking this all depends on the details of the collector, but since property values aren't part of the containing object, I'd be really surprised to learn of a collector that would do that.)

Upvotes: 4

Related Questions