soshimee_
soshimee_

Reputation: 35

Get all instances of a class in JavaScript

I'm trying to get the instances of a class, but I can't find a way to do it. The instances are created before my script loads, so I can't just make a variable that stores the instances. I've tried changing prototype methods, which does work for some classes that call the methods all the time, but not all of them do, and changing all of the methods is very annoying. So, is there a way to get all the instances of a class, reliably and arbitrarily timed?

Upvotes: 0

Views: 618

Answers (2)

Paddy
Paddy

Reputation: 56

I don't know if you are using a framework, but you could define an array in a place where all the needed callees have access to. There you can store the instance via the constructor.

Here is an example:

"use strict";

var exampleInstances = [];

class Example{
    prop = "";
    
    constructor() {
        this.prop = "Example"+exampleInstances.length;
        exampleInstances.push(this);
    }
}

var eInstance = new Example();
var eInstance2 = new Example();
var eInstance2 = new Example();

for (var i=0; i<exampleInstances.length; i++) {
    console.log(exampleInstances[i].prop);
}

Upvotes: 0

Quentin
Quentin

Reputation: 944007

No. JavaScript doesn't have any features that would make that possible.

Normally, I'd approach this by modifying the constructor of the class to include something like instance_of_foo.push(this) but you don't appear to have control over the source code of the class so that wouldn't work for you.

Upvotes: 1

Related Questions