Duktape supports object finalization as a custom feature. A finalizer is called when an object is about to be freed, so that application code can e.g. free native resources associated with an object.
An object which has an internal finalizer property in its prototype
chain (or in the object itself) is subject to finalization before being
freed. The internal finalizer property is set using the Duktape.fin()
method with the object and the finalizer function as call arguments.
The current finalizer is read back by calling Duktape.fin()
with only the object as a call argument. A finalizer can also be set/get from
C code using the duk_get_finalizer()
and duk_set_finalizer()
API calls. A finalizer can be either an Ecmascript function or a Duktape/C function.
A finalizer is triggered when an unreachable object is detected by reference counting or mark-and-sweep. Finalizers are also executed for all remaining objects (regardless of their reachability status) when a heap is destroyed. This guarantees that a finalizer gets executed at some point before a heap is destroyed, which allows native resources (such as sockets and files) to be freed reliably.
The finalizer function is called with the target object as its sole argument. The finalizer may rescue the object by creating a live reference to the object before returning. The return value is ignored, and any errors thrown by the finalizer are silently ignored. A finalizer may be called multiple times (this may happen in special cases even when the object is not rescued by the finalizer). A finalizer should be careful to avoid e.g. freeing a native resource twice in such cases.
Finalizers cannot currently yield. The context executing the finalization can currently be any coroutine in the heap. (This will be fixed in the future.)
See How to use finalization for examples.