1

If you have a webpage and it has a bunch of objects in there is there a way to select all objects of a specific type?

For example, if you define Class A, and then you create 3 instances of A, is there a way to find all instances of Class A?

class A{

}

var a = new A()
var b = new A()
var c = new A()

Is there a way to find objects a,b,c?

Travis J
  • 81,153
  • 41
  • 202
  • 273
SamFisher83
  • 3,937
  • 9
  • 39
  • 52
  • 1
    No, there is not (or maybe there is, but it wouldn't be recommended). – Bergi Apr 12 '18 at 21:34
  • Why not just keep them in a list in the first place? What is your [actual problem](https://meta.stackexchange.com/q/66377)? – Bergi Apr 12 '18 at 21:35
  • I am trying to get the data structures in a page I did not write. – SamFisher83 Apr 12 '18 at 21:36
  • If you add every object you create to some collection when it's created, and then search that collection for `instanceof Classname` https://stackoverflow.com/questions/1249531/how-to-get-a-javascript-objects-class – mc01 Apr 12 '18 at 21:37
  • no, you have to save instances in an Array() or Set() to keep all references – Yukulélé Apr 12 '18 at 21:38
  • @SamFisher83 And what tool are you using to do that? A debugger? – Bergi Apr 12 '18 at 21:51
  • @SamFisher83 Do you have control over the code now (i.e. are you maintaining a page you didn't author, or do you just try to reverse-engineer a completely foreign page)? – Bergi Apr 12 '18 at 21:56

2 Answers2

1

You can iterate over all of the objects in window and check their constructor name:

class A {

}

var a = new A();
let b = new A();
const c = new A();
var d = new A();

for(var key in window){
  if(window[key] && window[key].constructor && window[key].constructor.name == "A"){
    console.log(key);
  }   
}

/*
    Output:
 a
 d
*/

Although this will only find elements that are defined using var in the global scope.

A better option (if you were the creator of the page) would be to add all of the elements you want to keep track of in a list or object as you created them.

Nick is tired
  • 6,860
  • 20
  • 39
  • 51
  • 2
    Note that this is not limited only to the global scope but to global scope and `var` - `let` or `const` will not be added to the global object. – ASDFGerte Apr 12 '18 at 21:46
0

If you can iterate through the set of objects you have, then you can use instanceofMDN. However, without collecting the objects as you instantiate them, it is highly unlikely you would be able to gather the set by just looking at the global namespace. Mostly because the namespace is busy, as well as the fact that any of these objects which were created inside of separate scopes will not be accessible through that avenue.

The best way to accomplish this would be to save the objects you would like to find in the future, and then when you want to find them, iterate the set using the instanceof operator.

Travis J
  • 81,153
  • 41
  • 202
  • 273