Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all instances of class in Javascript

I thought there would already be an answer for this but I can't seem to find one.. How can I run a particular class method on all instances of this class in Javascript?

This has to be done in a situation where I do not know the names of the instances. I think I could use some sort of static variable inside my class to store all instances, but this doesn't seem to exist in JS

So how to call my method on all existing instances of my class? Note : just for clarification : I'm not speaking about CSS classes, I'm speaking about objects.

Edit : By Class in Javascript, I mean the creation of a new object on a function:

function something()
{
}

var instance = new something();
like image 374
Vincent Duprez Avatar asked Oct 22 '13 19:10

Vincent Duprez


People also ask

How do you access a class in Javascript?

Classes Are Functions Classes are declared with the class keyword. We will use function expression syntax to initialize a function and class expression syntax to initialize a class. We can access the [[Prototype]] of an object using the Object. getPrototypeOf() method.


2 Answers

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)
like image 113
0BLU Avatar answered Nov 12 '22 21:11

0BLU


Keyword 'static' could be used in classes now (but check support), ...

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

class Point{
    constructor(x, y){
        this.x = x;
        this.y = y;
        Point.all.push(this);
    }
    destroy(){
        let i = Point.all.indexOf(this);
        Point.all.splice(i, 1);
    }
    static all = [];
}

var p1 = new Point(1, 2);
var p2 = new Point(54, 33);
var p3 = new Point(297, 994);

console.log(JSON.stringify(Point.all)); //[{"x":1,"y":2},{"x":54,"y":33},{"x":297,"y":994}]

p2.destroy();
console.log(JSON.stringify(Point.all)); //[{"x":1,"y":2},{"x":297,"y":994}]
like image 42
honzar Avatar answered Nov 12 '22 21:11

honzar