mirror of https://github.com/svaarala/duktape.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
1.8 KiB
63 lines
1.8 KiB
<h1 id="finalization">Finalization</h1>
|
|
|
|
<p><b>(This section is incomplete.)</b></p>
|
|
|
|
<h2>Overview of finalization</h2>
|
|
|
|
<p>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 <code>Duktape.fin()</code>
|
|
method with the object and the finalizer function as call arguments.
|
|
The current finalizer is read back by calling <code>Duktape.fin()</code>
|
|
with only the object as a call argument.</p>
|
|
|
|
<p>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. The finalizer may be
|
|
triggered by either reference counting or mark-and-sweep.</p>
|
|
|
|
<p>Finalizers cannot currently yield. The context executing the finalization
|
|
can currently be any coroutine in the heap. (This will be fixed in the future.)
|
|
</p>
|
|
|
|
<!-- FIXME: comment on whether or not finalizers are run multiple times -->
|
|
|
|
<h2>Example</h2>
|
|
|
|
<p>Finalization example:</p>
|
|
<pre class="ecmascript-code">
|
|
// finalize.js
|
|
var a;
|
|
|
|
function init() {
|
|
a = { foo: 123 };
|
|
|
|
Duktape.fin(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')
|
|
Duktape.gc();
|
|
</pre>
|
|
|
|
<p>If you run this with the Duktape command line tool (with the default
|
|
Duktape profile), you'll get:</p>
|
|
<pre>
|
|
$ duk finalize.js
|
|
refcount finalizer
|
|
finalizer, foo -> 123
|
|
mark-and-sweep finalizer
|
|
Cleaning up...
|
|
</pre>
|
|
|
|
|