simo.filipo
simo.filipo

Reputation: 31

JavaScript - Get all objects that are instances of a specific class

I am not sure it is possible but I will try my luck.

Is it possible in JavaScript to find all objects that are instances of a specific class?

For example:

var obj1 = new MyClass();
var obj2 = new MyClass();
var obj3 = new MyClass();

I want to specify the class name "MyClass" and to get "obj1,obj2,obj3" in response.

How can I do that?

Upvotes: 3

Views: 10319

Answers (4)

Andreas Rau
Andreas Rau

Reputation: 336

You can do it like this:

function MyClass(){};

MyClass.prototype.test = function(){
   console.log('TEST');
};

function MyClassFactory(){
  this.instances = [];
};

MyClassFactory.prototype.create = function(){
  let tmp = new MyClass();
  this.instances.push(tmp);
  return tmp;
};

MyClassFactory.prototype.get = function(i){
  return this.instances[i];
};

MyClassFactory.prototype.getAll = function(){
  return this.instances;
};

let factory = new MyClassFactory();

let obj1 = factory.create();
let obj2 = factory.create();
let obj3 = factory.create();

let test1 = factory.get(0);

let test2 = factory.getAll();

for(let t of test2){
  t.test();
}

test1.test();

Upvotes: 1

Mohan Kumar
Mohan Kumar

Reputation: 631

You can only if you made some modification to the constructor

example:

var MyClassInstances = [];
var MyClass = function() { //constructor
   MyClassInstances.push(this); //push the new instance
}

thats it!. But be aware that it might become memory leak. so, you have to remove the reference from MyClassInstances when the objects are not needed.

Upvotes: 0

kimy82
kimy82

Reputation: 4495

Imagine this situation.

function M(){}
var m = new M();

Then you van do something like

for(let f in window){ if(window[f] instanceof M){console.log("founded"+f);}}

And you will find your object.

Hope that helps

Upvotes: 0

Patrick Vogt
Patrick Vogt

Reputation: 916

As far as I know, this doesn't work. You could save your objects in an array and iterate over it to retrieve all objects of class MyClass.

var objects = [new MyClass(), new MyClass(), new MyClass()];
function getObjectsOfClass(objects, clazz) {
   var objArr = [];
   for (var i = 0; i < objects.length; i++) {
       if (objects[i] instanceof clazz) {
           objArr.push(objects[i];
       }
   }
   return objArr;
}

Upvotes: 0

Related Questions