Reputation: 5985
Not sure how to phrase that question, but basically, I have an object constructor:
function myObject(name, type, size) {
this.name = name;
this.type = type;
this.size = size;
}
Then I create all of the objects (could be in the hundreds if I continue this pet project)
var newObject1 = new myObject("test name", "test type", "test size");
var newObject2 = new myObject("foo name", "foo type", "foo size");
var newObject3 = new myObject("bar name", "bar type", "bar size");
//etc.
Now, is there a loop that allows me to iterate through each object that comes from the myObject
constructor? I tried using this:
console.log(Object.getOwnPropertyNames(myObject));
but of course I don't know how to iterate through each object. Is there a way to do this?
Upvotes: 0
Views: 359
Reputation: 707716
The Javascript runtime does not provide any facility to iterate all objects of a particular type. If you really need to do this, then you will have to keep track of all such objects in some sort of data structure (probably an array).
In fact, if you're creating hundreds of objects all with uniquely named variables, then that's a red flag right there that you probably should be writing your code to use an array of those objects and access them by array index rather than each by uniquely named variable. This will also make your code a lot more compact.
Though it is sometimes frowned upon in Javascript (because it defeats garbage collection for individual instances until they are removed from the array), you can also make the object just keep track of it's own list of objects by having the constructor just add each newly created object to a list.
function myObject(name, type, size) {
this.name = name;
this.type = type;
this.size = size;
myObject.list.push(this);
}
myObject.list = [];
// to iterate all myObject instances
for (var i = 0; i < myObject.list.length; i++) {
// myObject.list[i]
}
Note: you could also maintain the ability to create an object that was not put in the list, but just creating a factory function that create the object and puts it in the list:
function myObject(name, type, size) {
this.name = name;
this.type = type;
this.size = size;
}
var listOfMyObject = [];
function makeMyObject(name, type, size) {
var o = new myObject(name, type,size);
listOfMyObject.push(o);
return o;
}
// to iterate all myObject instances
for (var i = 0; i < listOfMyObject.length; i++) {
// listOfMyObject[i]
}
Upvotes: 3
Reputation: 32511
Store a reference to each object then print that collection.
var myObjects = [];
function myObject(name, type, size) {
this.name = name;
this.type = type;
this.size = size;
myObjects.push(this);
}
// A bunch of new myObject()...
console.log(myObjects);
Upvotes: 0