(This section is incomplete.)
An object which has an internal finalizer property in its prototype chain (or the object itself) is subject to finalization before being freed. The internal finalizer property is set using __duk__.setFinalizer() method. The finalizer may be triggered by either reference counting or mark-and-sweep.
The finalizer method is called with the target object as its sole argument. The method may rescue the object by creating a live reference to the object before returning. The return value is ignored; similarly, any errors thrown by the finalizer are ignored.
Finalizers cannot currently yield. The context executing the finalization can currently be any coroutine in the heap. (This will be fixed in the future.)
Finalization example:
// finalize.js var a; function init() { a = { foo: 123 }; __duk__.setFinalizer(a, function (x) { print('finalizer, foo ->', x.foo); }); } // create object, reference it through 'a' init(); // delete reference, refcount triggers finalization immediately print('refcount finalizer'); a = null; // mark-and-sweep finalizing happens here (at the latest) if // refcounting is disabled print('mark-and-sweep finalizer') __duk__.gc();
If you run this with the Duktape command line tool (with the default Duktape profile), you'll get:
$ duk finalize.js refcount finalizer finalizer, foo -> 123 mark-and-sweep finalizer Cleaning up...