This question is similar to this this one, except I do not want to do it in chrome code.
In javascript (running in the browser) I want to keep track of all objects that have been created with a specific construct. Easy, I could do it like this:
var listObjects = [];
function Object() {
listObjects.push(this);
}
Object.prototype = {
// class members
};
which is fine, except objects are kept even when they are not used anymore (the garbage collector keeps them because in listObjects there is still a reference) creating memory leaks. Now, I could add a “removeObject” function removing an object from the list, but that would require the user to manually call whenever an objects get out of scope.
Now this could be solved if
- there would be weak references
- one could find out how many references there are to one object
- one could define an automatically called destructor
Unfortantly, according to my research, none of these exist in javascript (at least not when it is supposed to run in the browser).
Can anyone think of another way of doing this that works in javascript, or some javascript feature that I missed that could be used to do this?
I don’t think there’s any language support for this in JavaScript or that there’s any support for weak-references, at least not in browser environments.
However, you could attempt something (pretty, pretty, pretty ugly…) keeping your idea of a
function Object()override, but having it write to an invisible<div>on the screen the details of the object to track.There you go: tracking without holding actual references for objects. But you’d still need to implement a few query functions to retrieve information from that div and clear it over-time, or you’d have a leak as well.
Or you could do what you suggest: create a general purpose constructor and a general purpose destructor, but that’d require you to call them explicitly to remove objects from your list. But if any unexpected occurs, your destructors won’t get called so you’d probably end up leaking a lot and in unexpected ways.
Curious to know if others can think of alternatives.