As you know, JavaScript does not have deterministic object destruction. The JavaScript garbage collector is fully automatic and asynchronous. Although PJSR has a gc()
function that you can call to dispose of unreferenced objects, it works as a hint to the JavaScript engine, which is not necessarily executed when you perform the function call.
In the case of controls (Control
and its derived objects), the situation is particularly complex regarding object destruction since controls typically generate many deep dependencies, including hierarchical parent-child object relations, sizer dependencies, and event handlers. This means that, in general, there is no way to force the disposal of a control object, which will generally happen asynchronously after its parent Dialog
object is destroyed, with no guarantees during script execution.
My recommendation is to forget about this. Just generate as many controls as you need dynamically and use the delete
keyword as appropriate to remove unused object properties. You can also assign null
to unused properties to facilitate their garbage collection (make sure controls are not visible before deleting them or assigning null to their identifiers). Call gc( true/*exhaustive*/ )
occasionally to try to influence the garbage collector if you wish, although this usually won't work as you expect. Unless you create many thousands of complex controls in your script, there should be no practical problems. All unreferenced objects will be automatically deleted somewhere after your script terminates.