AlexWei AlexWei - 11 days ago 6
TypeScript Question

Destroy an circular-reference instance in typescript?

Say I have code like following:

class A
{
b: B;
constructor()
{
this.b = new B(this);
}
}

class B
{
a: A;
constructor(a: A)
{
this.a = a;
}
}
let a= new A()


When I want to destroy instance of a:

1 Should I just

a=null;


or

a.b.a=null;
a=null;


?

2 Is there any way to write code to test results? Say some code to detect instance number of some class in the memory?

Answer

If there's no reference to a or b it will be marked as unreachable by the garbage collector and be cleaned together, you don't have to do anything manually.

You can find more about how garbage collectors work in javascript here.