Get all instances of class in Javascript

Sorry for such a late reply, but I found myself trying to achieve this and I think this may be a simpler answer.

Say you want all instances of class MyClass, only get instances created at top window level (not including instances created inside a closure):

for (var member in window)
{
    if (window[member] instanceof MyClass)
        console.info(member + " is instance of MyClass");
}

You'll have to provide a custom implementation.

I would do something like this :

function Class() {
    Class.instances.push(this);
};
Class.prototype.destroy = function () {
    var i = 0;
    while (Class.instances[i] !== this) { i++; }
    Class.instances.splice(i, 1);
};
Class.instances = [];

var c = new Class();
Class.instances.length; // 1
c.destroy();
Class.instances.length; // 0

Or like this :

function Class() {};
Class.instances = [];
Class.create = function () {
    var inst = new this();
    this.instances.push(inst);
    return inst;
};
Class.destroy = function (inst) {
    var i = 0;
    while (Class.instances[i] !== inst) { i++; }
    Class.instances.splice(i, 1);
};

var c = Class.create();
Class.instances.length; // 1
Class.destroy(c);
Class.instances.length; // 0

Then you could loop through all instances like so :

Class.each = function (fn) {
    var i = 0, 
        l = this.instances.length;
    for (; i < l; i++) {
        if (fn(this.instances[i], i) === false) { break; }
    }
};

Class.each(function (instance, i) {
    // do something with this instance
    // return false to break the loop
});

You can create a static array and store it on your constructor function:

MyClass.allInstances = [];
MyClass.allInstances.push(this);

However, you need some way to figure out when to remove instances from this array, or you'll leak memory.


In Chrome 62+ you can use queryObjects from the console API - which will not work in native JavaScript code but in the console so it's great for debugging.

class TestClass {};
const x = new TestClass();
const y = new TestClass();
const z = new TestClass();
queryObjects(TestClass)