Search code examples
javascriptdestructorduktape

How can I do some clean up jobs when an object is being deleted / disposed in duktape?


I have a self-defined class that calls a native method to allocate buffer in the constructor method, like below:

MyClass = function () {
    this.buffer = native.alloc()
}

The buffer has to be released when the instance of MyClass is being deleted. Can I define a destructor in javascript like below? Would it be invoked when the GC happens?

MyClass.prototype.destructor = function () {
    native.free(this.buffer)
}

Solution

  • If your question is whether there are native methods to do what you described, then the answer is -no. There are no such methods.

    If your question - is whether it is possible to do it in any way, then the answer is - yes it is possible.

    If you control the entire code base of the project, then no one bothers you to come up with an architecture that would allow you to delete objects using only your API. As a result, if this is your API then you can do whatever you want.

    If you do not control the code, then there are several workarounds how to control the work with objects in JavaScript.

    The first thing to try is a proxy. This api allows you to control all manipulations with any object, provided that you can replace the original link to the object with your link with a proxy.

    The second thing to try is using Object.defineProperty. If the owner of the object did not specifically bother to close access to this API, then in fact you can hang on someone else's object any volume of your code that will allow you to control its behavior as you want.

    As a result, you will be able to implement the functionality you are asking about.