RAII in javascript

# Ben Manashirov (4 years ago)


It's easy to leak data in javascript because you need to call free(), or destroy() for various objects, for example when interfacing with OpenGL, emscripten, or some other object that needs to do cleanup beyond what a garbage collector can handle. I really want guaranteed destructors in javascript, it will make my life so much easier. I don't want anything similar to try-release that is introduced to Java because that doesn't solve the problem, it just moves the problem of having to call free/destroy to having to remember to list it in a try-release statement. Perhaps add a destructor() or destroy() as many libraries use destroy(). and if one exists treat the object with care to have it destroyed as soon as it's no longer referenced. Doing it for destroy() may break existing code so a another name would probably be better that people can migrate to, perhaps a special keyword in class{} interface 'destructor', and if one exists then special care will be given and a autogenerated 'destroy()' function is automatically created that a person can call to do destruction if they desire to do so earlier than when no more references are pointing to it.

I hope this discussion will lead to some solution.

Thank you.

# J Decker (4 years ago)

Chrome just put out a intent to ship Weak References

www.chromestatus.com/feature/5892186633666560, bugzilla.mozilla.org/show_bug.cgi?id=1367476#c6

Yes; for some things knowing when the related JS object goes away is really needed; but it's recommended to be used sparingly (although I can see one could instrument like everything that gets made to be able to track it)

# Gus Caplan (4 years ago)

Check this out: tc39/proposal

# MichaƂ Wadas (4 years ago)

thread - is there any discussion about soft references? Soft referenced objects can be garbage-collected if engine "decide that memory is low enough to warrant it".