Can I get all instances for prototype in javascript?

It's easy to get a prototype of an object, but is there a way to get all instances with a specific prototype?

Something like that:

var allAnimals = Animal.prototype.getInstances(); 

You can write your own code to track the created objects, but I'm wondering if there is a built-in method for this.

+6
source share
2 answers

you can get instances created in a window like

 var o = []; (for i in window) { if(window[i] instanceof Animal) o.push(window[i]); } 

but this code does not receive instances that were not created in the window ... you can create a method on Animal to create an instance from it and save it in the collection:

  +function () { var AnimalInstances = []; Animal = function (flag) { if (!flag) throw new Error("Invalid Instantiation"); }; Animal.Create = function () { var o = new Animal(true); AnimalInstances.push(o); return o; }; Animal.GetInstances = function () { return AnimalInstances; }; }(); 

or:

 +function () { var AnimalInstances = []; Animal = function () { AnimalInstances.push(this); } Animal.GetInstances = function () { return AnimalInstances; }; }(); 
0
source

You can try something like this

 function A(f){ this.field = f; A.instances.push(this); } A.instances = []; 

therefore after

 var one = new A(10), two=new A('123'); 

in A.instances will contain two created objects

0
source

All Articles