Circular referencing in Javascript reference counting

Viewed 1066

In Nicholas Zakas' book, he explains the problem of circular referencing when using reference counting for garbage collection in Javascript. He uses the following example:

function problem(){
    var objectA = new Object();
    var objectB = new Object();

    objectA.someOtherObject = objectB;
    objectB.anotherObject = objectA;
}

explaining that the two objects will never have the memory allocated to them freed since they have two references to them inside the function. I would like some clarification of how this works.

Clearly, there are two references to each object. The first object has both objectA and objectB.anotherObject pointing to it. The situation is analogous for the second object. So the reference count for each object is 2. But what happens when the function is exited? This isn't really described in the book. He says that the reference count is decremented whenever a reference to the value is overwritten with another value. I think this means:

function problem(){
    var objectA = new Object();
    var objectB = new Object();

    objectA.someOtherObject = objectB;
    objectB.anotherObject = objectA;
    objectA.someOtherObject = objectA; //<-- that if I were to do this, 
                                       //the reference count of the second object (B) 
                                       //would become 1, and 3 for the first object (A). 

}

But what happens when the function exits? As far as I understand, both objectA and objectB and their respective properties that reference each other will be destroyed, and thus, the two objects' reference counts will be decremented by 2. I don't see the "circular reference problem" that Zakas talks about. Could somebody explain what he's trying to say?

2 Answers
Related